小知识:nginx服务器配置解决ajax的跨域问题

在采用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 服务器代码:

?
1
2
3
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配置文件添加一下内容:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#
# 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 arent
#
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;
}
}
声明: 猿站网有关资源均来自网络搜集与网友提供,任何涉及商业盈利目的的均不得使用,否则产生的一切后果将由您自己承担! 本平台资源仅供个人学习交流、测试使用 所有内容请在下载后24小时内删除,制止非法恶意传播,不对任何下载或转载者造成的危害负任何法律责任!也请大家支持、购置正版! 。本站一律禁止以任何方式发布或转载任何违法的相关信息访客发现请向站长举报,会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。本网站的资源部分来源于网络,如有侵权烦请发送邮件至:2697268773@qq.com进行处理。
建站知识

小知识:linux 可执行文件与写操作的同步问题(文件读写操作产生的锁机制)

2023-4-25 3:59:22

建站知识

小知识:Nginx 多站点配置实例详解

2023-4-25 4:09:28

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索