在express,node.js中设置cookie并使用router.post获得json响应时出错

时间:2018-12-16 21:21:25

标签: javascript node.js express cookies

我正在尝试使用post方法设置cookie,以便执行一些数据库查询并将其放回cookie值,以及返回带有用户数据的json。 它有效,设置了cookie,我在http://localhost:8080上获取了json 但我从编译器收到一条消息:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

我如何解决它,以免出现此错误?

我的文件结构是: root / app.js

root / controllers / cookie.controller.js

root / routes / cookie.route.js

app.js

const express = require('express');
const cors = require('cors');
const cookieParser = require('cookie-parser');

const app = express();
const port = process.env.PORT || process.argv[2] || 8080;

app.use(cookieParser());
app.use(require('./routes/cookies'));
app.use(cors());

app.listen(port, () => console.log('cookie-parser demo is up on port: ' + port));

cookie.route.js

const express = require('express');

const cookieController = require('../controllers/cookies');

const router = express.Router();

router.use(require('cookie-parser')());

router.post('/', router.use(cookieController.getCookie));

module.exports = router;

cookie.controller.js

exports.getCookie = (req, res, next) => {
    let auth = req.cookies.auth;
    //...db queries, get userData

    let userData = {
        id: '123',
        token: 'sfsdfs34',
        email: 'user@gmail.com'
    };

    // if cookie doesn't exist, create it
    if (!auth) {
        res.status(200)
            .cookie('auth', userData.id)
            .json({ message: 'it works!', user: userData });
        req.cookies.auth = userData.id;
    }
    next();
};

2 个答案:

答案 0 :(得分:0)

setsid控制器末尾发送响应后,您正在修改请求cookie标头。您应该删除getCookie,然后使用req.cookies.auth = userData.id来发送响应。

res.cookie()

答案 1 :(得分:0)

从app.js删除cors后问题已解决