【发布时间】:2022-12-12 23:59:46
【问题描述】:
使用这个服务器配置
import Cors from 'cors';
const cors = Cors({
methods: ['GET', 'POST', 'HEAD'],
allowedHeaders: 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-Api-Authorize, X-Authorize',
credentials: true,
origin: (origin, callback) => {
console.log("*** TESTING", origin);
return callback(null, true); // debug, otherwise nothing works
},
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
});
const applyCors = async (req, res) => new Promise((resolve, reject) => {
cors(req, res, (result) => {
if (result instanceof Error) {
reject(result);
} else {
resolve(result);
}
});
});
export const apiMiddleware = handler => async (req, res) => {
await applyCors(req, res);
// ... req is extended with utils
return handler(req, res);
};
还有一个客户像这样获取请求
const response = await fetch(`/api/data`, {
credentials: 'same-origin', // also tried "include"
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Api-Authorize': 'secret'
},
method: 'GET'
});
服务器console.log总是印刷
*** 测试未定义
检查请求时,我看到了
X-Api-Authorize标头,但没有看到Origin。少了什么东西?
【问题讨论】:
-
'Content-Type': 'application/json',与method: 'GET'结合使用时毫无意义。 GET 请求没有正文,所以正文不能是 JSON。
标签: javascript cors fetch