![](/img/trans.png)
[英]CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response
[英]Being blocked by CORS: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response
我收到錯誤
Access to XMLHttpRequest at 'http://localhost:4000/api/investments' from origin 'http://localhost:5000' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
每當我嘗試使用以下 axios 命令將一些數據發布到我的 api 時
const [login, setLogin] = useState(
localStorage.getItem('userInfo')
? JSON.parse(localStorage.getItem('userInfo'))
: null
);
const config = {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${login.token}`,
},
};
await axios
.post(`${Config.SERVER_ADDRESS}/api/investments`, investmentObj, config)
.then((response) => {
console.log(investmentObj);
notify(`${response.data.name} investimento cadastrado com Sucesso`);
history.push(`/app/investment/${response.data._id}`);
})
.catch((err) => {
console.log(err);
notify(err.response.data, 'danger');
});
我不知道該怎么做,因為我正在使用以下中間件:
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', '*');
res.header('Access-Control-Allow-Credentials', true);
res.header(
'Access-Control-Allow-Headers',
'Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'
);
app.use(cors());
next();
});
我認為我的問題與標頭中的授權有關,因為我的其他 api 調用正在工作......希望你們中的任何一個都能幫助我處理這樣的預檢請求
我剛剛添加了以下代碼app.options('*', cors());
現在一切正常...查看 CORS npm https://www.npmjs.com/package/cors#enabling-cors-pre-flight
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', '*');
res.header('Access-Control-Allow-Credentials', true);
res.header(
'Access-Control-Allow-Headers',
'Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'
);
app.use(cors({ credentials: true, origin: true }));
next();
});
app.options('*', cors());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.