发布于 2017-05-21 21:08:00 | 178 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Nginx中文文档,程序狗速度看过来!

Nginx WEB服务器

Nginx 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器。 Nginx 是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru 站点开发的,第一个公开版本0.1.0发布于2004年10月4日。其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名。


本文给大家分享的是一个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 服务器代码:


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';
}
}



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务