国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 網(wǎng)站 > Nginx > 正文

nginx服務(wù)器通過配置來解決API的跨域問題

2024-08-30 12:28:56
字體:
供稿:網(wǎng)友

前言

最近在采用jquery ajax調(diào)用http請(qǐng)求時(shí),發(fā)現(xiàn)了一系列問題:

如采用firebug調(diào)試API請(qǐng)求(這個(gè)API是自己服務(wù)器的應(yīng)用),看到服務(wù)器明明返回200狀態(tài),response返回?cái)?shù)據(jù)也是json格式,但ajax返回的error。

在排除json數(shù)據(jù)格式不正確的原因之后,發(fā)現(xiàn)了ajax error函數(shù)返回“networkerror failed to execute ‘send' on ‘xmlhttprequest' failed to load ‘http //“ XMLHttpRequest.status=0,就是沒有初始化。

后來才知道是跨域問題(CORS),因?yàn)槌绦蛘{(diào)用的是遠(yuǎn)程服務(wù)器的API,服務(wù)器不允許跨域調(diào)用。如果只是簡單的方法,只需要在程序的response添加支持跨域的header添加屬性”Access-Control-Allow-Origin: * “即可。

如java 服務(wù)器代碼:

yourownvariable.setHeader("Access-Control-Allow-Origin:", "origin url of your site");yourownvariable.setHeader("Access-Control-Allow-Methods", "GET, POST,PUT");

如果是配置nginx服務(wù)器(如果是其他服務(wù)器,可以參考:I want to add CORS support to my server),需要在nginx.conf配置文件添加一下內(nèi)容:

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

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對(duì)VEVB武林網(wǎng)的支持。


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 察隅县| 大英县| 阿坝| 郎溪县| 天津市| 永昌县| 靖安县| 桃园县| 灌云县| 阿拉尔市| 富民县| 芜湖县| 上栗县| 巩义市| 云阳县| 胶南市| 武定县| 云梦县| 铁岭市| 鄂伦春自治旗| 贵德县| 河西区| 大冶市| 汾西县| 县级市| 新津县| 怀柔区| 五华县| 枣阳市| 南雄市| 谢通门县| 元朗区| 鄂温| 乌鲁木齐市| 连平县| 长岛县| 高淳县| 延津县| 盐池县| 庄浪县| 壶关县|