我正在尝试使用webservice prestashop(1.6)通过使用jquery函数getJSON()获取我的产品,但是在控制台的浏览器上,我收到以下错误:
XMLHttpRequest cannot load
http://www.pourquoilavie.org/api/products/?ws_key=XXXXXkeyXXXXXXXXX&io_format=JSON.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost' is therefore not allowed access.
我尝试在htaccess中添加“Header set Access-Control-Allow-Origin:*”,但没有成功。
我想知道是否有另一种设置标题的方法(除了使用带有header('Access-Control-Allow-Origin: *');
的php)
答案 0 :(得分:2)
在prestashop 1.6中,您可以尝试在
中添加此内容./prestafolder/webservice/dispatcher.php
出于安全原因,您可以输入域名
而不是星号header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Origin: http://example.com');
FYI
如果您仍然遇到问题或Unauthorized
消息,请尝试从
http://KEYTOKEN@example.com/api/
到
http://example.com/api/?ws_key=KEYTOKEN
答案 1 :(得分:1)
我自己解决了这个问题,我只是在webservice文件夹中的文件dispatcher.php上添加header('Access-Control-Allow-Origin: *');
答案 2 :(得分:0)
对我来说,我尝试使用React App,我必须在dispatcher.php中进行一些修改,并添加选项preflight 200 return
我在dispatcher.php标头中添加了
//to access from external browser
header('Access-Control-Allow-Origin: *');
header( 'Access-Control-Allow-Headers: Authorization, Access-Control-Allow-Headers,
Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-
Control-Request-Headers,Output-Format');
header( 'Access-Control-Allow-Methods: GET, OPTIONS, HEAD, PUT, DELETE');
header( 'Access-Control-Allow-Credentials: true');
然后在代码中进行如下修改
if ($method === 'OPTIONS') {
die('200');
ob_end_flush();
}else{
if (isset($_SERVER['PHP_AUTH_USER'])) {
....
}
答案 3 :(得分:0)
如果您使用的是Angular或类似框架,请根据您的环境在prestashop_folder/webservice/dispatcher.php
文件的第一行上修改并添加以下代码
// Allow from any origin
if(isset($_SERVER["HTTP_ORIGIN"]))
{
// You can decide if the origin in $_SERVER['HTTP_ORIGIN'] is something you want to allow, or as we do here, just allow all
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
}
else
{
//No HTTP_ORIGIN set, so we allow any. You can disallow if needed here
header("Access-Control-Allow-Origin: *");
}
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 600"); // cache for 10 minutes
if($_SERVER["REQUEST_METHOD"] == "OPTIONS")
{
if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_METHOD"]))
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT"); //Make sure you remove those you do not want to support
if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"]))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
//Just exit with 200 OK with the above headers for OPTIONS method
exit(0);
}