繁体   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