盡管對 CORS 問題提出了很多問題,但沒有一個對我有幫助。首先,我了解 CORS 是什么以及為什么它很重要。我不想禁用 CORS。我想正確使用它。我有一個 ReactJS 應用程序在http://localhost:3000. 此外,我的后端 NodeJS 應用程序運行在http://localhost:1234.我已經從我的 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.更新我發現我調用的 REST 端點是完全錯誤的。修復它解決了這個問題。概括如果您有我在問題中描述的這種設置,它應該可以正常工作。另外,我會選擇 @TJ Crowder 建議在我的 NodeJS 應用程序中使用的備用庫。
帶有 Express Server CORS 設置的 ReactJS
慕絲7291255
2022-07-15 09:38:57