總結一下近期遇到ajax跨域請求問題javascript
業務場景描述:java
操做過程當中出現的問題node
Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
對於出現OPTIONS請求的理解:
在跨域請求時,瀏覽器對於PUT,DELETE等方法,會先發送一次預檢請求,該請求頭的method就是OPTIONS,服務端須要對這個請求進行處理,瀏覽器獲得服務端支持該請求時,纔會發送真正的PUT請求。git
服務器最終配置github
//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() } }); //or app.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
以前!web
問題解決完了發現node提供瞭解決跨域問題的cors模塊。解決跨域問題很是方便,可是因爲node服務器只是本身在本地搭建用於測試用,工做中是和java開發配合,因此沒有用起來。ajax
github連接:corsexpress
示例代碼:json
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') })