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