【问题标题】:Angular app does not set cookies which come from expressAngular 应用程序不会设置来自 express 的 cookie
【发布时间】:2021-01-01 10:50:52
【问题描述】:

我正在尝试学习后端和前端,到目前为止我还不错。但是现在我有一个问题。

在我使用 Express 的后端中,我使用 res.cookie 发送 cookie,如下所示

auth.js (/auth 路由)

const register = asyncErrorWrapper(async (req, res, next) => {

    const {name, email, password} = req.body;
    const user = await User.create({
        name,
        email,
        password
    });
   sendJwtToClient(user, res);

});

tokenHelper.js

const sendJwtToClient = (user, res) => {

    // user modeline gore jwt olusturma

    const token = user.generateJwtFromUser();

    const {JWT_COOKIE, NODE_ENV} = process.env;

    return res
    .status(200)
    .cookie('access_token', token, {
        httpOnly:true,
        expires: new Date(Date.now() + parseInt(JWT_COOKIE) * 1000 * 60),
        secure: NODE_ENV === 'development' ? false : true
    })
    .json({
        success: true,
        access_token: token,
        data: {
            name: user.name,
            email: user.email
        },
        message: 'Your registration is succesful!'
    });
};

然后我在与 Auth Service 连接的 register.component 中收到 Angular 应用程序的响应

来自Register.component

registerUser() {

    this.sendButton.nativeElement.disabled = true;

    this._authService.registerUser(this.user).subscribe(
      res => {
         if(res.status === 200) {
           console.log(res);
         }
      }, err => {
        console.log(err);
        this.showError.nativeElement.className += ' alert alert-danger';
        this.errMessage = err.error.message;
        this.sendButton.nativeElement.disabled = false;
      })
  }

认证服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  _registerURI = 'http://localhost:3000/auth/register';
  _loginURI = 'http://localhost:3000/auth/login';

  constructor(private http: HttpClient) { }

  registerUser(user) {
    return this.http.post<any>(this._registerURI, user, {observe: 'response'});
  };

  loginUser(user) {
    return this.http.post<any>(this._loginURI, user, {observe: 'response'});
  };

};

当我点击注册按钮时,我得到了这个响应:response

顺便说一句,我在后端使用 cors 包。提前致谢。

我还可以共享其他代码,任何您想要的页面。我只是觉得这样就够了。

【问题讨论】:

    标签: node.js angular express cookies


    【解决方案1】:

    好的,明白了。

    问题是由于 cors 政策而发生的。要将 cookie 发送到前端,您需要引入 cors 包。

    这里是express使用的cors包的选项:

    app.use(cors( {
        origin: 'http://localhost:4200',
        allowedHeaders: ['Content-Type', 'Authorization'],
        credentials: true
    } ));
    

    这是发布注册的 Auth Service 方法

      registerUser(user) {
        return this.http.post<any>(this._registerURI, user, {observe: 'response', withCredentials: true});
      };
    

    【讨论】:

    • 这个解决方案不适合我
    猜你喜欢
    • 2017-06-20
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 2021-07-27
    相关资源
    最近更新 更多