預期
發送Content-Type為application/json的post請求不觸發跨域錯誤
- 客戶端請求
const params = {
a: 'a',
b: 'b',
}
//直接發送對象則Content-Type為application/json
axios.post(API_URL, params)
.then((res) => {
console.log(res)
})
- 后端配置
如果請求為簡單請求則不會出發 CORS 預檢請求,可直接在請求內配置Access-Control-Allow-Origin,Access-Control-Allow-Methods,Access-Control-Allow-Headers,來解決跨域問題
// 簡單請求
app.get('/API',(req,res,next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
...
})
如果Content-Type 的值僅限於下列三者之一視為簡單請求:
text/plain
multipart/form-data
application/x-www-form-urlencoded
本例Content-Type為application/json,則不屬於簡單請求,需要先發送預檢請求,所有直接在請求內設置以下配置是無效的.
設置了Access-Control-Allow-Origin", "*", 仍然會報錯:
Access to XMLHttpRequest at 'http://localhost:portA/API' from origin 'http://localhost:portB' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
app.post('/API',(req,res,next) => {
// res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
// res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
//無效
...
})
nodejs 解決方案
當觸發預檢請求時讓options請求快速結束,直接執行請求
const express = require("express");
const app = express();
//跨域配置需放在接口前面
app.use("/API", (req,res,next) => {
console.log('checking');
//設置允許跨域的域名,*代表允許任意域名跨域
res.header("Access-Control-Allow-Origin","http://localhost:port");
//允許的header類型
res.header("Access-Control-Allow-Headers","content-type");
//跨域允許的請求方式
res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
if (req.method.toLowerCase() == 'options')
res.send(200); //讓options嘗試請求快速結束
else
next();
})
app.get('/API',(req,res,next) => {...})
//或者
app.post('/API',(req,res,next) => {...})