【发布时间】:2020-05-11 09:35:51
【问题描述】:
这就是我配置服务器的方式
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const app = express();
const port = 3000;
app.use(cors());
app.use(bodyParser.json());
app.use(morgan(':method :url :status :res[content-length] - :response-time ms'));
现在,我想既然我使用了 cors 包,并且我为所有来源启用了它,我的请求将在我的应用程序中通过。嗯,它没有,因为每次我尝试向服务器发送请求时,都会给我一个 CORS 错误。
我正在使用有趣的绕过:我在端口3000(CRA 的端口)上启动我的服务器。如果我先启动服务器,然后启动我的 React 应用程序,CRA 会提示我切换到不同的端口。现在,我可以向我的服务器发送请求,而无需使用 CORS。但是,如何在我的应用中正确启用 CORS?
来自浏览器的完整错误:
TypeError: "NetworkError when attempting to fetch resource.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/accounts. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/accounts. (Reason: CORS request did not succeed).
更新:我有
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
})
在我的服务器中,但由于某种原因,在发送响应时,它没有标头?
【问题讨论】:
-
你能分享完整的错误吗?在浏览器的控制台中返回。
-
@BENARDPatrick 刚刚编辑了我的代码以获得完整的错误
-
您的客户端是否在本地主机上运行?
-
是的,但在不同的端口上
-
响应的 HTTP 状态码是什么?您可以使用浏览器开发工具中的网络窗格进行检查。是 4xx 还是 5xx 错误而不是 200 OK 成功响应?
标签: node.js reactjs express cors