【发布时间】:2015-06-25 14:49:42
【问题描述】:
我正在使用 CORS 请求将数据发布到不同域上的 php 脚本。我收到错误消息:
跨域请求被阻止:同源策略不允许读取 'mydomain' 的远程资源(原因:CORS 标头 'Access-Control-Allow-Origin' 缺失)。
我已经使用以下代码在 php 中设置了标题。
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
我也试过这个post中的代码
这是供参考的javascript代码
$.ajax(url, {
type:"POST",
dataType:"json",
data: {
name:"something"
},
success:function(data, textStatus, jqXHR) {
alert("success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("failure");
}
});
响应标头
Age:1
Cache-Control:max-age=900
Connection:keep-alive
Content-Length:356
Content-Type:text/html; charset=utf-8
Date:Sun, 19 Apr 2015 04:26:27 GMT
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
请求标头
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:14
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
DNT:1
Host:www.jurney.co
Origin:http://isabelinc.in
Pragma:no-cache
Referer:http://isabelinc.in/jurney/testcors.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36
但我没有运气。 任何帮助表示赞赏
【问题讨论】:
-
能否添加查询的 HTTP 标头?我想你会首先看到
OPTIONS请求(响应中需要 CORS 标头),然后POST请求(也需要 CORS 标头)。 -
我已将标题添加到问题中。我在请求中没有看到任何选项,只有一个 POST
-
我在响应中看不到任何 CORS 标头。当您的浏览器在 isabelinc.in 上并使用 ajax 调用调用 jurney.co 时,jurney.co 必须添加 CORS 标头以告诉浏览器是的,它允许 isabelinc.in(或“*”)这样做。如果您确定
headers("Acess-Control...")在这里,请查找说Warning: Cannot modify header information - headers already sent的PHP 警告。 -
当我直接或通过 ajax 查询调用 jurney.co 链接时,我看不到标题。我确实看到了
Server: Microsoft-IIS/7.5X-AspNet-Version: 4.0.30319和X-Powered-By: ASP.NET:你确定这是正确的 php 服务器吗?
标签: php cross-domain cors