ajax跨域請求問題總結

總結一下近期遇到ajax跨域請求問題javascript

業務場景描述:java

  1. 移動端頁面放在阿里雲服務器
  2. 進入頁面後, 須要訪問另外一個服務器的接口,ajax請求使用用GET,POST,PUT等方法
  3. 服務端須要進行cors配置

操做過程當中出現的問題node

  1. 發送PUT請求時,請求頭的method變成OPTIONS, 且瀏覽器控制檯給出提示: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提供瞭解決跨域問題的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')
})
相關文章
相關標籤/搜索