Magento 2的Ajax添加到购物车功能是通过前端JavaScript与后端API交互实现的购物车操作方式,无需刷新页面即可完成商品添加。
当Magento 2的前端页面与后端API不在同一个域名下时,浏览器会触发"同源策略"安全限制,导致Ajax请求失败。具体表现为:
在Magento 2的后端添加跨域支持:
// 创建或修改 app/code/Vendor/Module/etc/webapi_rest/di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\Webapi\Rest\Response\RendererFactory">
<arguments>
<argument name="renderers" xsi:type="array">
<item name="json" xsi:type="string">Magento\Framework\Webapi\Rest\Response\Renderer\Json</item>
</argument>
</arguments>
</type>
</config>
然后创建CORS中间件:
// app/code/Vendor/Module/etc/di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\Webapi\Rest\Request">
<plugin name="cors_headers" type="Vendor\Module\Plugin\CorsHeaders"/>
</type>
</config>
// app/code/Vendor/Module/Plugin/CorsHeaders.php
namespace Vendor\Module\Plugin;
class CorsHeaders
{
public function beforeDispatch(
\Magento\Framework\Webapi\Rest\Request $subject,
\Magento\Framework\App\ActionInterface $action
) {
$response = $action->getResponse();
$response->setHeader('Access-Control-Allow-Origin', '*');
$response->setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
$response->setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
return null;
}
}
修改Ajax请求为JSONP格式:
require(['jquery'], function($) {
$.ajax({
url: 'https://your-magento-domain.com/rest/V1/carts/mine/items',
type: 'POST',
dataType: 'jsonp',
data: {
cartItem: {
sku: 'product-sku',
qty: 1,
quote_id: 'cart-id'
}
},
success: function(response) {
console.log('Product added to cart');
}
});
});
在前端服务器设置代理,将Ajax请求转发到Magento后端:
// 前端代码
require(['jquery'], function($) {
$.ajax({
url: '/proxy/magento-cart',
type: 'POST',
data: {
sku: 'product-sku',
qty: 1
},
success: function(response) {
console.log('Product added to cart');
}
});
});
确保前端请求包含正确的CSRF令牌和内容类型:
require(['jquery', 'mage/url'], function($, urlBuilder) {
var serviceUrl = urlBuilder.build('rest/V1/carts/mine/items');
$.ajax({
url: serviceUrl,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
cartItem: {
sku: 'product-sku',
qty: 1,
quote_id: 'cart-id'
}
}),
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
success: function(response) {
console.log('Product added to cart');
}
});
});
这种跨域Ajax添加到购物车功能常见于:
通过以上解决方案,可以确保Magento 2的Ajax添加到购物车功能在不同域名下正常工作。
没有搜到相关的文章