nginx配置ajax请求跨域
生活随笔
收集整理的這篇文章主要介紹了
nginx配置ajax请求跨域
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
首先通過mozilla文檔了解跨域原理:
web跨域的方式有幾種,常見的方案有web服務后端代碼層級解決與nginx配置層面解決,這里我以nginx配置層面為例。
一般瀏覽器跨域請求的時候會先發起option預檢測請求,當請求得到確認后,才開始真正發送請求。
因此,首先應該解決預請求的跨域問題,以下是nginx針對預請求的配置:
HTTP 204 成功狀態響應碼表示該請求已經成功了,但是客戶端客戶不需要離開當前頁面。默認情況下 204 響應是可緩存的。一個 ETag 標頭包含在此類響應中。
前端使用jquery發起ajax跨域攜帶cookie的請求代碼:
效果:
接著在nginx配置正式請求的跨域:
重啟nginx后,正式請求效果:
nginx配置內容:
location / {if ($request_method = 'OPTIONS') {add_header 'Access-Control-Allow-Origin' 'https://test.xx.com';add_header Access-Control-Max-Age 1728000;add_header 'Access-Control-Allow-Credentials' 'true';add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';add_header Content-Type' 'text/plain; charset=utf-8';add_header Content-Length 0;return 204;}add_header 'Access-Control-Allow-Origin' 'https://test.xx.com';add_header 'Access-Control-Allow-Credentials' 'true';add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';client_max_body_size 20m;proxy_pass http://xxx.xxx.10.200:8095;proxy_set_header Host $host;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}?
總結
以上是生活随笔為你收集整理的nginx配置ajax请求跨域的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java Jsoup不能获取完整响应内容
- 下一篇: jquery无法删除一级域名cookie