Search code examples
node.jsangularexpresscookies

Angular app does not set cookies which come from express


I am trying to learn backend and frontend and so far I was okey. But now I have a problem.

In my backend which I use Express, I send cookie with res.cookie as shown below

auth.js (/auth route)

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!'
    });
};

Then I get response with Angular app in register.component which is connected with Auth Service

from 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;
      })
  }

Auth Service

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'});
  };

};

Well I get this response when I click register button: response

Btw I use cors package on backend. Thanks in advance.

I can also share other codes, pages whatever you want. I just thought that this is enough.


Solution

  • Okey, got it.

    The problem occurred because of the cors policy. To send cookies to the front-end you need to let in cors package.

    Here is the options of cors package that used by express:

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

    And this is the Auth Service method posting registration

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