3

I am working on full stack project. And I can not set cookie in my browser.

  • My back end is written with node.js and express framework, running at localhost:3002.
  • My front end is using react.js, running at localhost:3000.
//server side
app.use(cookieParser());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cors());
.....
.....
router.post('/login', (req, res) => {

    User.findOne({'email': req.body.email}, (err, user) => {
        // find the email
        if (!user) return res.status(404).json({loginSuccess: false, message: 'Auth failed, email not found!'});

        // check the password
        user.comparePassword(req.body.password, (err, isMatch) => {
            if (!isMatch) return res.status(400).json({loginSuccess: false, message: 'Wrong password!'});

            // generate a token
            user.generateToken((err, user) => {
                if (err) return res.status(400).send(err);
                res.cookie('w_auth', user.token,  { domain: 'http://localhost:3000', secure: true }).status(200).json({loginSuccess: true, user: user});
                console.log(res);
            })
        })
    })
});

//client side
export const loginUser = (dataToSubmit, history) => dispatch => {

    axios.post(`${USER_SERVER}/login`,dataToSubmit)
        .then(resposne => {

            dispatch({
                type: actionTypes.LOGIN_USER,
                payload: resposne.data
            });
            history.push('/user/dashboard');
        })
        .catch(err => dispatch({
            type: actionTypes.GET_ERRORS,
            payload: err.response.data
        }));
};

The response header for /api/users/login route contains

'Set-Cookie':'w_auth=eyJhbGciOiJIUzI1NiJ9.N...

but the cookie isn't saved in browser (document.cookie is empty).

Meanwhile I tried using Postman to send a post request to /api/users/login, and I found the cookie in Postman's Cookies. So I guess that browser refuse to save the cookie.

Anyone can help solve this?

Harrymissu
  • 305
  • 2
  • 5
  • 16

1 Answers1

0

If secure is set to true the cookie must be transmitted through an HTTPS connection, otherwise the cookie isn't transmitted

https://www.owasp.org/index.php/SecureFlag

Daphoque
  • 3,588
  • 1
  • 13
  • 22