簡體   English   中英

React + Express CORS錯誤400錯誤請求

[英]React + Express CORS error 400 Bad Request

我正在嘗試從React應用程序向Express后端發出異步請求。 但是我得到了通常的“ CORS問題:錯誤的請求”:

圖像

我知道Express的CORS插件,因此我已經從Node Plugin Manager安裝了cors ,並應用於后端index.js例如:

...
import express from 'express';
import cors from 'cors';
...

const app = express();
...

const whitelist = [
  'http://localhost:3000'
]
const corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

app.use(cors(corsOptions));
...

app.listen(4000, () => console.log('server running on port 4000);

因此,我嘗試使用Fecth API從后端服務器檢索數據:

class Component extends React.Component {
  render() {
    const { componentId } = this.props.match.params;

    (async () => {
      const query = `
        query {
          getComponent(id: "${componentId}") {
            type
          }
        }
      `;

      const options = {
        method: 'POST',
        body: JSON.stringify(query)
      };

      const component = await fetch('http://localhost:4000/graphql', options);

      console.log(component);
    })();

    return (
      <h1>Hola</h1>
    );
  }
}

export default Component;

我也嘗試過設置headers: { 'Content-Type': 'application/json }mode: corscrossOrigintrue

每次使用任何配置我都會收到相同的錯誤。 任何意見表示贊賞。

在開發環境中,您可以在package.json文件中添加代理:“ proxy”:“ http:// localhost:4000

您的package.json應該如下所示:

"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
 },
  "proxy": "http://localhost:4000",
  "eslintConfig": {
    "extends": "react-app"
  },

如前所述,當您使用localhost域時,Chrome不允許發出請求。 使用代理,不是圖像,css,js等的所有內容都將考慮使用代理。 因此,當您發出請求時,只需使用fetch('/ graphql')即可, 而無需使用domain

https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM