我正在全栈项目中。而且我无法在浏览器中设置cookie。


我的后端是用运行在localhost:3002的node.js和express框架编写的。
我的前端使用的是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发送发帖请求,并在Postman的Cookies中找到了cookie。
所以我想浏览器拒绝保存cookie。

有人可以帮助解决这个问题吗?

最佳答案

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

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

10-01 21:13
查看更多