我不能从服务器接收cookie时,我调用API形式的Angular ,但当我在 Postman 测试它可以.(我的后端是NestJS)

yjghlzjz  于 2023-03-08  发布在  Postman
关注(0)|答案(1)|浏览(153)

这是我的登录后台代码

async loginUser(loginUserDTo : LoginUserDto, response : Response): Promise<any> {
    let responseC = new ResponseStandard()
    let user = await this.userModel.findOne({where: {email: loginUserDTo.email}})
    const jwt = await this.jwtService.signAsync({id: user.id})
    response.cookie('jwt', jwt, {httpOnly: false })

    if (!user) {
        responseC.error_code = "400"
        responseC.error_message = "Invalid User"
        throw new BadRequestException('Invalid User')
    } 
    if (!await bcrypt.compare(loginUserDTo.password, user.password)) {
      responseC.error_code = "400"
      responseC.error_message = "Password not correct"
      throw new BadRequestException('Password not correct')
    }
    else {
        responseC.success = true
        responseC.result = user
    }
    return responseC
  }

当我在 Postman 身上测试这个的时候,它的工作正常
enter image description here
这是我的前端代码。当我调用它从这个。我不能接收cookie

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http'

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent {
  constructor( private http:HttpClient){}
  onSubmit(data:any)
  {
     this.http.post('http://localhost:8000/users/login',data,{observe: 'response', responseType: 'json',withCredentials: true})
     .subscribe((result)=>{
      console.warn("result",result)
    })
    console.warn(data)
  
  }
}

enter image description here
我希望它能像我在后端测试时一样正常接收

8gsdolmq

8gsdolmq1#

我觉得这可能跟CORS有关,你提到是nestjs,这是他们的文档https://docs.nestjs.com/security/cors
基本上,如果你的cors头不正确,cookies会被拒绝。在这种情况下,你可能会在浏览器控制台中看到一个关于Access-Control-Allow-Origin不正确的错误。
我相信你想要的是

const app = await NestFactory.create(AppModule, { 
cors: {
 origin: ["angular url"],
credentials: true
} 
});

相关问题