【发布时间】: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和通配符 (*) 来源是不允许的。