ajax跨域请求问题总结
生活随笔
收集整理的這篇文章主要介紹了
ajax跨域请求问题总结
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
總結一下近期遇到ajax跨域請求問題
業務場景描述:
操作過程中出現的問題
對于出現OPTIONS請求的理解:
在跨域請求時,瀏覽器對于PUT,DELETE等方法,會先發送一次預檢請求,該請求頭的method就是OPTIONS,服務端需要對這個請求進行處理,瀏覽器得到服務端支持該請求時,才會發送真正的PUT請求。
服務器最終配置
//node跨域配置 app.all('*', function(req, res, next) {let reqOrigin = req.header["origin"];if (req.method === 'OPTIONS') {console.log(req.method)var headers = {};// IE8 does not allow domains to be specified, just the *// headers["Access-Control-Allow-Origin"] = req.headers.origin;headers["Access-Control-Allow-Origin"] = "*";headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";headers["Access-Control-Allow-Credentials"] = false;headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";res.writeHead(200, headers);res.end();} else {console.log(req.method)res.header("Access-Control-Allow-Origin", "*");next()} });//orapp.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By",' 3.2.1') res.header("Content-Type", "application/json;charset=utf-8"); next(); });需要注意的一點是,app.all部分的代碼需要放置在app.use之前!
node的cors模塊
問題解決完了發現node提供了解決跨域問題的cors模塊。解決跨域問題非常方便,但是由于node服務器只是自己在本地搭建用于測試用,工作中是和java開發配合,所以沒有用起來。
github鏈接:cors
示例代碼:
var express = require('express') var cors = require('cors') var app = express()app.use(cors())app.get('/products/:id', function (req, res, next) {res.json({msg: 'This is CORS-enabled for all origins!'}) })app.listen(80, function () {console.log('CORS-enabled web server listening on port 80') })轉載于:https://www.cnblogs.com/foxNike/p/7698309.html
總結
以上是生活随笔為你收集整理的ajax跨域请求问题总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【BZOJ 2460 元素】
- 下一篇: ZKW线段树入门