我一直在尝试通过本地开发服务器(Web-pack开发服务器)上的浏览器中运行的React应用程序进行api调用(在本地主机上运行带有nodejs和express的nodejs)。一切运行良好,直到我尝试调用该API。它们都在单独的端口上运行。
我尝试将cors标头(由MDN推荐)添加到post调用(来自浏览器中的应用程序)和Nodejs API的响应中,但是这些都不能解决问题。
api调用的代码(在浏览器中):
const headers = {
'Content-Type': 'application/json',
'access-token': '',
'Access-Control-Allow-Origin': '*',
}
export default async () => {
try {
const body = JSON.stringify({
test: true,
})
const response = await fetch('http://localhost:1337/internal/provider/check_email_exist', {
method: 'POST',
headers,
body,
})
console.log(response)
} catch (e) {
return e
}
}
API中间件(在nodejs中):
// Verify All Requests
app.use(VerifyToken)
// Compress
app.use(compression())
// Helmet middlware
app.use(helmet())
// Body Parser
app.use(bodyParser.urlencoded({
extended: false,
}))
app.use(bodyParser.json())
预期结果是只给出200个状态码并用数据响应。
实际输出为:
OPTIONS http://localhost:1337/internal/provider/check_email_exist 404 (Not Found)
Access to fetch at 'http://localhost:1337/internal/provider/check_email_exist' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
答案 0 :(得分:1)
由于您使用的是webpack-dev-server
,因此可以使用proxy
选项DevServerProxy。
您的配置将如下所示:
// webpack.config.js
devServer: {
proxy: {
'/internal': 'http://localhost:1337'
}
}
由于在您的问题上看不到您的express
路由,我正在推测代理路由,如果您的API
居住在/internal
端点上,那么您应该像下面那样修改React代码这个:
const response = await fetch('/internal/provider/check_email_exist', {
method: 'POST',
headers,
body,
})
如您所见,我省略了https://localhost:1337
,因为proxy
的{{1}}选项将处理此问题并将其重定向到webpack-dev-server
。希望这会帮助你。干杯,辛辣的。
编辑
正如对问题的评论所指出的那样,您应该在http://localhost:1337
服务器(而不是客户端)上设置标头,对于此任务,您可以使用cors-middleware包。
答案 1 :(得分:0)
如果您遇到飞行前错误,这可能会有所帮助。
我的完整配置:
const cors = require('cors');
const express = require('express');
const { createProxyMiddleware: proxy } = require('http-proxy-middleware');
...
const logLevel = 'info';
const ip = require('ip').address();
const proxyOptions = {
xfwd: true,
target,
changeOrigin: true,
logLevel,
cookieDomainRewrite: {
'*': 'localhost',
},
headers: {
'X-Forwarded-For': ip,
'X-Node': 'true',
},
};
const backNginxApp = express();
backNginxApp.use(
cors({
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
origin: 'http://localhost:3000',
optionsSuccessStatus: 200,
credentials: true,
})
);
backNginxApp.use('/api', proxy(proxyOptions));
API:const target = 'https://someapi.com'
运行在http://localhost:3000