Cross Server user not receiving the actual value of cookies

Viewed 23

I am trying to send/retrieve cookies from one system to another system. Here is my FE code (Angular 4) for setting a cookie

document.cookie = 'student_exists=true;SameSite=None;Secure'

// it will be true or false depending upon whether the student exists or not. this is my route in node.js -> xx.com/api/retrievecookie This is my function

retrievecookie () {
try {
            let student_exists = false;
            if (req.cookies && req.cookies.student_exists && 
                req.cookies.student_exists === 'true') {
                student_exists = true
            }
            const data = {'student_exists': student_exists};
            res.json(data);
        } catch (e)  {
            console.log(e);
            res.send({'error': 'error in your request'});
        }
}

Here is my index file (node js)

const cookieParser = require('cookie-parser');
app.use(function (req, res, next) {
    console.log(req);
    const origin = req.headers.origin;
    if (req.url === '/api/studentprofile/verify') {
       res.setHeader('Access-Control-Allow-Origin', origin);
    } else {
        res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
    }
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

When I am hitting the URL & same browser from my own system, I am getting the true values i.e. either true or false.

When the other user with different server or browser, ther user is always getting false, Here is other user's code

>            $.ajax({
>               type: "GET",
>               url: "xx.com/api/retrievecookie",
>               xhrFields: {
>                     withCredentials: true
>                 },
>               success: function(data) {
>                   console.log(data);
>               },
>               error: function(data) {
>                   alert(data);
>               }
       });

please help me fix this issue.

0 Answers
Related