【问题标题】:React + Express CORS error 400 Bad RequestReact + Express CORS 错误 400 错误请求
【发布时间】:2019-09-15 02:38:36
【问题描述】:

我正在尝试从 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);

所以我尝试使用 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

每次使用任何配置时,我都会遇到相同的错误。任何 cmets 都表示赞赏。

【问题讨论】:

  • 你在用chrome吗?那么也许您的问题是,Chrome 不支持来自本地主机(bugs.chromium.org/p/chromium/issues/detail?id=67743)的 cors。用其他浏览器试过吗?
  • 我也在 Firefox 中尝试过,但错误响应为 500,再次与“cors”有关。

标签: javascript reactjs express fetch-api


【解决方案1】:

在开发环境中,您可以在 package.json 文件中添加代理: "代理": "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

【讨论】:

  • 好的......它有点工作,我有另一个问题,但这个问题已经解决......谢谢。
猜你喜欢
  • 2019-07-23
  • 2018-04-27
  • 2017-05-31
  • 2018-11-04
  • 2018-07-08
  • 2017-03-23
  • 2021-09-28
  • 2017-08-04
  • 1970-01-01
相关资源
最近更新 更多