nginx服務器配置解決ajax的跨域問題
在采用jquery ajax調用http請求時,發(fā)現了一系列問題:
如采用firebug調試API請求(這個API是自己服務器的應用),看到服務器明明返回200狀態(tài),response返回數據也是json格式,但ajax返回的error。
在排除json數據格式不正確的原因之后,發(fā)現了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'; } }
相關文章
Nginx在Windows下的安裝及環(huán)境配置(將nginx作為服務運行)
這篇文章主要介紹了Nginx在Windows下的安裝及環(huán)境配置,主要是將nginx作為服務運行,需要的朋友可以參考下2018-11-11nginx報錯:[emerg] getpwnam(“www“)failed問題及解決
這篇文章主要介紹了nginx報錯:[emerg] getpwnam(“www“)failed問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-03-03nginx環(huán)境下配置ssl加密(單雙向認證、部分https)
這篇文章主要介紹了nginx環(huán)境下配置ssl加密(單雙向認證、部分https),具有一定的參考價值,感興趣的小伙伴們可以參考一下。2016-11-11