当前位置: 移动技术网 > 网络运营>服务器>nginx > nginx服务器通过配置来解决API的跨域问题

nginx服务器通过配置来解决API的跨域问题

2019年04月19日  | 移动技术网网络运营  | 我要评论

圣光的个人空间,满堂红中山,1yys

前言

最近在采用jquery ajax调用http请求时,发现了一系列问题:

如采用firebug调试api请求(这个api是自己服务器的应用),看到服务器明明返回200状态,response返回数据也是json格式,但ajax返回的error。

在排除json数据格式不正确的原因之后,发现了ajax error函数返回“networkerror failed to execute ‘send' on ‘xmlhttprequest' failed to load ‘http //“ xmlhttprequest.status=0,就是没有初始化。

后来才知道是跨域问题(cors),因为程序调用的是远程服务器的api,服务器不允许跨域调用。如果只是简单的方法,只需要在程序的response添加支持跨域的header添加属性”access-control-allow-origin: * “即可。

如java 服务器代码:

yourownvariable.setheader("access-control-allow-origin:", "origin url of your site");


yourownvariable.setheader("access-control-allow-methods", "get, post,put");

如果是配置nginx服务器(如果是其他服务器,可以参考:i want to add cors support to my server),需要在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';
}
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网