0

I have node.js with express backend with some endpoints, all works fine testing with curl or postman, but on my client-side with angular on the http.post request i get the response correctly, but no cookie is saved. I've tried changing my localhost dns, after some try i'm ended up using 127.0.0.1:4200 client and 127.0.0.1:3000 backend.

backend code:

const express = require('express');
const bodyParser = require('body-parser');
const webpush = require('web-push');
const cors = require('cors');
const cookieParser = require('cookie-parser');

const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(cookieParser());

app.post(path, /*here I call my function*/);
[...]
/*in my function i set cookie with these lines*/
res.cookie('userData',
   {token: token,},{ httpOnly: true, secure: false }
);

client code:

[...]
constructor(private http: HttpClient) {}
[...]
/*request on my button click*/
this.http
      .post<AuthResponse>(path, bodyReq)

who cares about these pieces of code, lets see the result.

descrpition1

in the response header i can see the set-cookie, and when i switch to the cookie tab of the request i can see it correctly, but..

description2

something is telling chrome to don't save my cookie, he received it!! I've already check on web about cors, domains, cookie settings. Nothing works for me. Thanks for any help.

rever
  • 178
  • 2
  • 13

1 Answers1

0

the BENARD Patrick tips was right!!

To solve my problem add withCredentials both on client and server (using this solution I've had to specify the domain)

client code:

return this.http
      .get<AuthResponse>(path, {
        withCredentials: true,
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': 'www.dns_to_127.0.0.1.com:4200',
        }),
      })

server code:

app.use(
  cors({
    origin: 'http://www.dns_to_127.0.0.1.com:4200',
    credentials: true,
  })
);

credentials: Configures the Access-Control-Allow-Credentials CORS header. Set to true to pass the header

rever
  • 178
  • 2
  • 13