Amir Allahdadian
Amir Allahdadian

Reputation: 48

angular doesn't send cookie to server automatically

I'm using Angular 15 for front-end and node.js version 18.10.0 and express version 4.17.2 for back-end.

I want to send the cookie i have in my browser cookies back to the server that sent it. the cookie is an authentication token which i saved using the header 'Set-Cookie' and it was saved successfully and i see it at browser dev tools at application cookies.

why the cookie is not sent from browser to the server in the cookie header?

I need to send the token (if it exists) with every request to server.

I have set these headers in my server:

  res.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
  res.setHeader("Access-Control-Allow-Credentials", "true");
  res.setHeader("Allow-Origin-With-Credentials", "true");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, X-XSRF-TOKEN, Cookie"
  );
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, PUT, OPTIONS");

I set the angular HTTP Option that enables HTTP Requests with credentials in an Interceptor for every request and provided it at app.module:

intercept(req: HttpRequest<any>, next: HttpHandler) {
    return next.handle(
      req.clone({
        withCredentials: true,
      })
    );
  }

in the server after user signs in, I create and send the token in the code below:

exports.userSignIn = async (req, res) => {
  try {
    const user = await User.findOne({ where: { email: req.body.email } });

    if (user) {
      bcrypt.compare(req.body.password, user.password, async (error, same) => {
        if (!error) {
          if (same) {
            const token = jwt.sign(
              {
                name: user.name,
                phoneNumber: user.phoneNumber,
                email: user.email,
                id: user.id,
              },
              jwtUserSecret,
              {
                expiresIn: "24h",
              }
            );

            res.cookie("XSRF-TOKEN", token, { maxAge: 86400000 });

            res.status(200).json({
              emailExistance: true,
              passwordValid: true,
              expiresIn: 86400,
            });
          } else {
            res.status(401).json({
              emailExistance: true,
              passwordValid: false,
              expiresIn: null,
            });
          }
        } else {
          throw error;
        }
      });
    } else {
      res.status(401).json({
        emailExistance: false,
        passwordValid: null,
        expiresIn: null,
      });
    }
  } catch (error) {
    console.error(error);

    res.status(401).json({
      emailExistance: null,
      passwordValid: null,
      expiresIn: null,
    });
  }
};

here is the response of code above the server sends:

enter image description here

here is an example of a request header sent to server after cookie was saved:

enter image description here

why the cookie is not sent from browser to the server in the cookie header?

Upvotes: 1

Views: 629

Answers (1)

Amir Allahdadian
Amir Allahdadian

Reputation: 48

As mentioned in the comments:

the domain is not the same: localhost:3000 vs. 127.0.0.1:3000. Even though they point to the same destination, cookies are separated between both domains

I changed the route from http://127.0.0.1:3000/ to http://localhost:3000/ and cookie was sent automatically and my problem was solved.

Upvotes: 1

Related Questions