【问题标题】:CORS AngularJS/NestJSCORS AngularJS/NestJS
【发布时间】:2022-01-26 15:01:48
【问题描述】:

试图登录,但它给了我这个错误:

从源“http://localhost:4200”访问“http://localhost:3000/api/auth/login”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:当请求的凭据模式为“包含”时,响应中的“Access-Control-Allow-Origin”标头的值不能是通配符“*”。 XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

注册完美。

main.ts NestJS

import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { cors: true });
  app.useGlobalPipes(
    new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }),
    );

    app.use((req, res, next) => {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
      res.header('Access-Control-Allow-Headers', 'Content-Type, Accept');
      next();
  });

  app.enableCors({
      allowedHeaders:"*",
      origin: "*"
  });
  await app.listen(3000);
}
bootstrap();

login.component.ts

import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {Router} from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  form!: FormGroup;

  constructor(
    private formBuilder: FormBuilder,
    private http: HttpClient,
    private router: Router
  ) {
  }

  ngOnInit(): void {
    this.form = this.formBuilder.group({
      email: '',
      password: ''
    });
  }

  submit(): void {
    this.http.post('http://localhost:3000/api/auth/login', this.form.getRawValue(), {
      withCredentials: true
    }).subscribe(() => this.router.navigate(['/']));
  }
}

【问题讨论】:

  • 错误信息非常清楚。 withCredentials: true 和通配符 (*) 来源是不允许的。

标签: angular cors nestjs


【解决方案1】:

说的很清楚

当请求的凭据模式为“包含”时,响应中的“Access-Control-Allow-Origin”标头的值不能是通配符“*”。

您需要将原点设置为特定值。有什么理由不使用app.enableCors() 而不是自定义中间件?否则,只需设置

res.header('Access-Control-Allow-Origin', 'http://localhost:4200');

【讨论】:

  • 您缺少http:// 位。
猜你喜欢
  • 2020-02-18
  • 2013-01-24
  • 1970-01-01
  • 2018-11-29
  • 2021-08-11
  • 2013-12-03
  • 2015-04-12
  • 2013-11-02
  • 2013-07-19
相关资源
最近更新 更多