React + Express CORS错误400错误请求

问题描述 投票:-1回答:1

我试图从React应用程序向Express后端发出异步请求。但我得到了通常的“CORS问题:错误请求”:

Imagen

我知道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);

所以我尝试使用Fetch 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: corscrossOrigin设置为true

每次使用任何配置我都会得到相同的错误。任何评论都表示赞赏。

javascript reactjs express fetch-api
1个回答
0
投票

在开发环境中,您可以在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'),而不使用域。

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

© www.soinside.com 2019 - 2024. All rights reserved.