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

首頁 > 網站 > Nginx > 正文

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

2024-08-30 12:22:34
字體:
來源:轉載
供稿:網友
這篇文章主要給大家介紹了關于nginx服務器是如何配置來解決API跨域問題的相關資料,文中介紹的非常詳細,對大家具有一定的參考學習價值,需要的朋友們下面來一起看看吧。

前言

最近在采用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';}}

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對武林網之家的支持。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 黄龙县| 响水县| 明光市| 浦县| 从化市| 彰武县| 怀来县| 东台市| 沅江市| 定边县| 彩票| 安化县| 乐都县| 乳源| 朔州市| 绥棱县| 和平区| 左权县| 青川县| 罗定市| 舞钢市| 西城区| 白银市| 繁峙县| 临沂市| 华阴市| 乌拉特前旗| 理塘县| 屏东县| 集安市| 高邮市| 象山县| 栖霞市| 建始县| 临澧县| 卢湾区| 阳春市| 鹤庆县| 宁陕县| 三穗县| 常山县|