React + Express CORS 错误 400 错误请求

React + Express CORS error 400 Bad Request

我正在尝试从 React 应用向 Express 后端发出异步请求。但我得到了通常的 "CORS issue: Bad request":

Imagen

我知道 Express 的 CORS 插件,所以我从节点插件管理器安装了 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: corscrossOrigin 设置为 true

我每次使用任何配置都会遇到同样的错误。任何意见表示赞赏。

在开发环境中可以在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"
  },

如前所述,Chrome 不允许在您使用 localhost 域时发出请求。使用代理,所有不是图像、css、js 等的东西都会考虑代理。因此,当您发出请求时,只需使用 fetch('/graphql'), 没有域 .

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