【问题标题】:cannot enable cors in nestJs [duplicate]无法在nestJs中启用cors [重复]
【发布时间】: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


【解决方案1】:

看起来您正在向localhost:3500/api/v1/users/login 发出请求,它没有任何方案。

改用http://localhost:3500/api/v1/users/login

【讨论】:

    猜你喜欢
    • 2020-02-18
    • 2019-03-06
    • 2018-11-29
    • 2016-12-20
    • 2018-12-03
    • 2015-02-19
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多