我正在尝试使用以下代码进行AJAX调用(CORS):
$.ajax({
type: "POST",
url: 'http://localhost/MySpace',
success: function(result) {
console.log(result);
},
error: function() {
console.log("error");
},
});
我正在运行以上代码:
http://127.0.0.1/Test/index.html
在http://localhost/MySpace
编写的PHP代码如下:
<?php
header("Access-Control-Allow-Origin: *");
echo "Hello";
?>
根据我的理解,这应该有效。但是我收到了这个错误:
XMLHttpRequest cannot load http://localhost/MySpace. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1' is therefore not allowed access.
我应该怎么做才能使这个工作?或者我做错了什么?
根据调试请求的建议,我尝试发出curl请求:
curl -i http://127.0.0.1/MySpace/
作为回应,我可以看到Access-Control-Allow-Origin
被标记为*
:
HTTP/1.1 200 OK
Date: Fri, 13 May 2016 05:59:19 GMT
Server: Apache/2.4.18 (Unix) OpenSSL/1.0.2g PHP/5.6.19 mod_perl/2.0.8-dev Perl/v5.16.3
X-Powered-By: PHP/5.6.19
Access-Control-Allow-Origin: *
Content-Length: 5
Content-Type: text/html; charset=UTF-8
根据评论,我将以下代码添加到.htaccess
:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
@Edit:
这是我的回复标题:
HTTP/1.1 301 Moved Permanently
Date: Fri, 13 May 2016 09:26:44 GMT
Server: Apache/2.4.18 (Unix) OpenSSL/1.0.2g PHP/5.6.19 mod_perl/2.0.8- dev Perl/v5.16.3
Location: http://localhost/elasticservice/
Content-Length: 240
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1
这是我的请求标题:
POST /elasticservice HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 0
Cache-Control: max-age=0
Accept: */*
Origin: http://127.0.0.1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36
Referer: http://127.0.0.1/test/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,hi;q=0.6
答案 0 :(得分:1)
您已经允许CORS Origin,因此要访问跨域3标头(Origin, Methods, Headers)
必须,请参阅下面的示例标题
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
@update:你可以尝试这个解决方案
header('Access-Control-Allow-Origin: *');
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
$headers=getallheaders();
@$ACRH=$headers["Access-Control-Request-Headers"];
header("Access-Control-Allow-Headers: $ACRH");
}
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
答案 1 :(得分:0)
尝试以下网址:
$.ajax({
type: "POST",
url: 'http://127.0.0.1/MySpace',
success: function(result) {
console.log(result);
},
error: function() {
console.log("error");
},
});