【发布时间】:2019-09-15 02:38:36
【问题描述】:
我正在尝试从 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: cors 和crossOrigin 设置为true。
每次使用任何配置时,我都会遇到相同的错误。任何 cmets 都表示赞赏。
【问题讨论】:
-
你在用chrome吗?那么也许您的问题是,Chrome 不支持来自本地主机(bugs.chromium.org/p/chromium/issues/detail?id=67743)的 cors。用其他浏览器试过吗?
-
我也在 Firefox 中尝试过,但错误响应为 500,再次与“cors”有关。
标签: javascript reactjs express fetch-api