小编Cod*_*ews的帖子

在服务器上设置请求后,Cors 仍然阻止请求

即使我在服务器上启用了 CORS,Chrome CORS 仍然会阻止 API。我阅读了官方文档来启用CORS。我的后端是用 Nest.js 编写的,前端是用 Ionic/Angular 编写的。

除了官方文档之外,我还尝试了各种其他用户建议的解决方案,例如设置选项,但都不起作用。

使用 postman 时 API 调用工作得非常好。

这是服务器代码:

const app = await NestFactory.create(AppModule);
  const options = {
    origin: '*',
    headers: '*',
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    preflightContinue: true,
    optionsSuccessStatus: 204,
    credentials: true,
  };
  app.enableCors(options);
  await app.listen(3000);
Run Code Online (Sandbox Code Playgroud)

这是 http 调用:

  this.http.post(`${this.config.serverAddress}/api/auth/login`,{'username': 'test', 'password': 'password'})
        .subscribe(d=>{
            console.log(d);
        })
Run Code Online (Sandbox Code Playgroud)

最后,这是 chrome 错误消息:

zone-evergreen.js:2952 Access to XMLHttpRequest at 'localhost:3000/api/auth/login' from origin 'http://localhost:8100' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, …
Run Code Online (Sandbox Code Playgroud)

javascript node.js typescript angular nestjs

0
推荐指数
1
解决办法
589
查看次数

标签 统计

angular ×1

javascript ×1

nestjs ×1

node.js ×1

typescript ×1