前言
前言
Ajax请求遇到的跨域网络错误
近期在使用jQuery发起Ajax HTTP请求的过程中,遇到了一系列异常状况:
例如使用Firebug调试位于自身服务器的API请求时,尽管服务端返回了200状态码且响应数据格式为正确的JSON,但前端Ajax却触发了error回调。
在排除JSON数据格式错误的可能性后,发现Ajax的error函数返回了“networkerror failed to execute ‘send' on ‘xmlhttprequest' failed to load ‘http //”的错误信息,其XMLHttpRequest.status值为0,表明请求未成功初始化。
通过响应头解决跨域问题的原理
随后查明原因是跨域限制(CORS)。由于程序调用的是远程服务器的API,而该服务器默认禁止跨域访问。若采用简单处理方式,只需在程序的响应中添加支持跨域的Header属性“Access-Control-Allow-Origin: * ”即可。
Java服务器端的CORS配置示例
以Java服务器代码为例:
yourownvariable.setHeader("Access-Control-Allow-Origin:", "origin url of your site");
yourownvariable.setHeader("Access-Control-Allow-Methods", "GET, POST,PUT");
Nginx服务器端的CORS配置方法
若采用Nginx服务器进行配置(其他服务器可参考相关文档),需在nginx.conf配置文件中加入以下内容:
#
# Wide-open CORS config for nginx
#
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
}
}
总结
总结
以上内容即为本文的全部讲解,希望能为各位的学习或工作提供协助。如有任何疑问,欢迎留言交流,感谢对本站的支持。