【发布时间】:2022-02-09 21:56:10
【问题描述】:
我正在尝试连接 react 和 NestJS,但出现 cors 错误 我来自浏览器(谷歌浏览器)的请求被 cors 阻止。 我什至无法记录传入的请求!!!!!! 在浏览器网络选项卡中,我看到来自 xhr 的 CORS 错误 在控制台标签中我看到了
Access to XMLHttpRequest at 'localhost:3500/api/v1/users/login' from origin
'http://localhost:3001' has been blocked by CORS policy: Cross origin requests are only supported
for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
Axios Error: Network Error
at createError (createError.js:16:1)
at XMLHttpRequest.handleError (xhr.js:84:1)
xhr.js:177 POST localhost:3500/api/v1/users/login net::ERR_FAILED
我试过 { cors: true } 和 app.enableCors(); 和
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
和
const corsOptions: CorsOptions = {
allowedHeaders: ['origin', 'x-requested-with', 'content-type', 'accept', 'authorization'],
credentials: true,
origin: ['http://localhost:3001', 'http://localhost:3000'],
}
app.enableCors(corsOptions);
【问题讨论】:
-
我的前端是 Reactjs,我使用 Axios 进行 HTTP 调用。我认为浏览器正在阻止 Axios 发送请求;因为我无法在 NestJs 中记录任何内容
-
错字,您忘记了在客户端代码中输入的 URL 前面的
//、http://或https://。 -
问题出在这儿!!我因为没有得到正确的结果而头疼;谢谢人
标签: javascript reactjs axios cors nestjs