慕絲7291255
2022-07-15 09:38:57
盡管對 CORS 問題提出了很多問題,但沒有一個對我有幫助。首先,我了解 CORS 是什么以及為什么它很重要。我不想禁用 CORS。我想正確使用它。我有一個 ReactJS 應用程序在http://localhost:3000. 此外,我的后端 NodeJS 應用程序運行在http://localhost:1234.我已經(jīng)從我的 NodeJS 應用程序中啟用了 CORS,如下所示:app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "http://localhost:3000") // update to match the domain you will make the request from res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept") next()});這是我的請求在 ReactJS 應用程序中的樣子:axios .post(this.props.endPoint, formData) .then(res => { console.log("Successfull"); this.setState({ loginOk: true }); }) .catch(err => { console.log(err); });這是登錄頁面。當我提交請求時,我在瀏覽器控制臺中看到以下錯誤。Access to XMLHttpRequest at 'http://localhost:1234/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.更新我發(fā)現(xiàn)我調(diào)用的 REST 端點是完全錯誤的。修復它解決了這個問題。概括如果您有我在問題中描述的這種設(shè)置,它應該可以正常工作。另外,我會選擇 @TJ Crowder 建議在我的 NodeJS 應用程序中使用的備用庫。
1 回答
www說
TA貢獻1775條經(jīng)驗 獲得超8個贊
問題可能是您鏈接到的后續(xù)路由next沒有意識到它們正在處理OPTIONS請求(預檢)。對預檢的響應應該只是標題。
如果是這樣,您可以像這樣修復它:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3000") // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
if (req.method === "OPTIONS") {
res.status(200).end();
} else {
next()
}
});
...前提是中間件優(yōu)先于其他中間件,等等。
也就是說,您可能會查看一個久經(jīng)考驗的中間件,而不是自己動手做。cors似乎很受歡迎。
添加回答
舉報
0/150
提交
取消
