【问题标题】:res.cookie is not working to keep cookie in browserres.cookie 无法将 cookie 保存在浏览器中
【发布时间】:2019-09-07 05:38:35
【问题描述】:

我正在从事全栈项目。而且我不能在我的浏览器中设置cookie。

  • 我的后端是用 node.js 和 express 框架编写的,运行在 localhost:3002。
  • 我的前端使用 react.js,在 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
        }));
};

/api/users/login 路由的响应头包含

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

但 cookie 未保存在浏览器中(document.cookie 为空)。

同时我尝试使用 Postman 向 /api/users/login 发送 post 请求,我在 Postman 的 Cookies 中找到了 cookie。 所以我猜浏览器拒绝保存cookie。

谁能帮忙解决这个问题?

【问题讨论】:

  • 这似乎是一个跨域问题
  • 这是一个跨域问题。我用Answer here修复了它

标签: node.js reactjs express


【解决方案1】:

如果 secure 设置为 true,则 cookie 必须通过 HTTPS 连接传输,否则不会传输 cookie

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

【讨论】:

    猜你喜欢
    • 2020-08-24
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 2020-02-27
    • 1970-01-01
    • 2014-09-18
    • 2021-03-09
    相关资源
    最近更新 更多