简体   繁体   中英

React + Express CORS error 400 Bad Request

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":

Imagen

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);

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;

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.

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

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"
  },

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM