亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

帶有 Express Server CORS 設置的 ReactJS

帶有 Express Server CORS 設置的 ReactJS

慕絲7291255 2022-07-15 09:38:57
盡管對 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 應用程序中使用的備用庫。
查看完整描述

1 回答

?
www說

TA貢獻1775條經驗 獲得超8個贊

問題可能是您鏈接到的后續路由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()

  }

});

...前提是中間件優先于其他中間件,等等。


也就是說,您可能會查看一個久經考驗的中間件,而不是自己動手做。cors似乎很受歡迎。


查看完整回答
反對 回復 2022-07-15
  • 1 回答
  • 0 關注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號