常规情况下跨域,只需要服务端设置响应头 即可
res.header('Access-Control-Allow-Origin', 'http://localhost:3001'); // *
这个情况,普通的get请求已经解决,但是
但在post请求时加之传递数据,此时已经是 非简单请求了
const params = {data: 1};
axios.post("http://localhost:3000/list", params)
应为 content-type: application/json;
这个时候也能通过前端设置请求 header content-type 转成简单请求
axios.post("http://localhost:3000/list", params, {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
// "Authorization": "1231"
}
})
但是如果前端自定义header 的 Authorization ,这个时候有出现跨域了;
我的问题是:
- 怎么保持Content-Type 是application/json;的情况下支持跨域
- 当头部有自定义字段Authorization时候,怎么跨域
补充:
下面这个配置 对第二个问题无效
res.setHeader('Access-Control-Allow-Headers', "Authorization");
对option处理
app.all("*", function (req, res, next) {
res.header(
"Access-Control-Allow-Headers",
"Authorization,Accept,Content-Type,Referer,sec-ch-ua,sec-ch-ua-mobile,User-Agent"
);
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("Allow", "PUT,POST,GET,DELETE,OPTIONS");
next();
});
app.post("/list", function (req, res) {
res.header("Access-Control-Allow-Origin", "http://localhost:3001");
res.header("Access-Control-Expose-Headers", "Authorization");
res.header("Content-Type", "application/json;charset=utf-8");
res.json({
list: [
{
id: 1,
name: "ranck",
time: "2020-02-03",
},
{
id: 1,
name: "ranck",
time: "2020-02-03",
},
{
id: 1,
name: "ranck",
time: "2020-02-03",
},
],
});
});
option截图
post 复杂请求截图
报错截图