React + Express CORS错误400错误的请求 [英] React + Express CORS error 400 Bad Request

查看:83
本文介绍了React + Express CORS错误400错误的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从React应用向Express后端发出异步请求.但是我得到了通常的"CORS问题:错误的请求":

I am trying to make asynchronous requests from a React app to an Express backend. But I am getting the usual "CORS issue: Bad request":

图像

我知道Express的CORS插件,因此我已经从Node Plugin Manager中安装了 cors ,并应用于了我的后端 index.js ,例如:

I am aware of CORS plugin for Express so I have installed cors from Node Plugin Manager and applied to my backend index.js like:

...
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从后端服务器检索数据:

So I have tried with Fecth API to retrieve data from the backend server:

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;

我也尝试将 header:{'Content-Type':'application/json} mode:cors crossOrigin 设置为 true .

I have tried also setting headers: { 'Content-Type': 'application/json }, mode: cors and crossOrigin to true.

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

I get the same error everytime with any configuration. Any comments are appreciated.

推荐答案

在开发环境中,您可以在package.json文件中添加代理:"proxy":" http://localhost:4000 "

In the dev environment you can add the proxy in the package.json file: "proxy": "http://localhost:4000"

您的package.json应该如下所示:

Your package.json should look like this:

"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'),不带域.

As already said, Chrome doesn't allow to make request when you are using localhost domain. Using a proxy, everything that isn't an image, css, js, etc, will consider the proxy. So when you will make the request just use fetch('/graphql'), without the domain.

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

这篇关于React + Express CORS错误400错误的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆