得到!错误 [ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置 headers |表达

Getting! Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client | Express

我收到错误 [ERR_HTTP_HEADERS_SENT]:在将它们发送到客户端后无法设置 headers,然后在执行 POST 请求时出现一些包含错误位置的长列表是快递路线。我看到了类似的答案,得到了很多,但我找不到我遗漏的地方。

我在此附上特定 POST 请求的代码示例。

    .post(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => {
    Favorites.findOne({user: req.user._id})
    .then((favs)=> {
        if(!favs) {
            Favorites.create({user: req.user._id, dishes: req.body})
            .then((favs)=> {
                console.log('Favs created: ', favs);
                res.statusCode = 200;
                res.setHeader('Content-Type', 'application/json');
                res.json(favs);
            }, (err) => next(err))
            .catch((err) => next(err));
        }
        else {
            var noofids = req.body.length;
            for (var i=0; i<noofids ; i++) {
                if(favs.dishes.indexOf(req.body[i]._id) > -1) {
                    res.json('It is already in the dishes');
                }
                else {
                    favs.dishes.push(req.body[i]._id);
                    favs.save()
                    .then((doc) => {
                        Favorites.findById(doc._id)
                        .populate('User').populate('Dishes')
                        .then((fav) => {
                            res.statusCode = 200;
                            res.setHeader('Content-Type', 'application/json');
                            res.json(fav);
                        }, (err) => next(err))
                        .catch((err) => next(err));
                    }, (err) => next(err))
                    .catch((err) => next(err));
                }
            }
        }
    }, (err) => next(err))
    .catch((err) => next(err));

})

当执行 if 部分时,它执行时没有错误,但当执行 else 时,它显示一长串错误。

POST /favorites/ 200 7.864 ms - 29
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:518:11)
    at ServerResponse.header (E:\CourseraMERN\NodeJS\conFusionServer\node_modules\express\lib\response.js:767:10)
    at ServerResponse.send (E:\CourseraMERN\NodeJS\conFusionServer\node_modules\express\lib\response.js:170:12)
    at done (E:\CourseraMERN\NodeJS\conFusionServer\node_modules\express\lib\response.js:1004:10)
    at Object.exports.renderFile (E:\CourseraMERN\NodeJS\conFusionServer\node_modules\jade\lib\index.js:374:12)
    at View.exports.__express [as engine] (E:\CourseraMERN\NodeJS\conFusionServer\node_modules\jade\lib\index.js:417:11)
    at View.render (E:\CourseraMERN\NodeJS\conFusionServer\node_modules\express\lib\view.js:135:8)
    at tryRender (E:\CourseraMERN\NodeJS\conFusionServer\node_modules\express\lib\application.js:640:10)
    at Function.render (E:\CourseraMERN\NodeJS\conFusionServer\node_modules\express\lib\application.js:592:3)
    at ServerResponse.render (E:\CourseraMERN\NodeJS\conFusionServer\node_modules\express\lib\response.js:1008:7)
    at E:\CourseraMERN\NodeJS\conFusionServer\app.js:84:7
    at Layer.handle_error (E:\CourseraMERN\NodeJS\conFusionServer\node_modules\express\lib\router\layer.js:71:5)
    at trim_prefix (E:\CourseraMERN\NodeJS\conFusionServer\node_modules\express\lib\router\index.js:315:13)
    at E:\CourseraMERN\NodeJS\conFusionServer\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (E:\CourseraMERN\NodeJS\conFusionServer\node_modules\express\lib\router\index.js:335:12)
    at next (E:\CourseraMERN\NodeJS\conFusionServer\node_modules\express\lib\router\index.js:275:10)

如何解决这个问题?谢谢!

确保 return 每个 res.json() 语句,否则代码将继续执行它下面的行,并且您有代码在多个位置设置 headers,这会导致错误:

.post(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => {
    Favorites.findOne({user: req.user._id})
    .then((favs)=> {
        if(!favs) {
            Favorites.create({user: req.user._id, dishes: req.body})
            .then((favs)=> {
                console.log('Favs created: ', favs);
                res.statusCode = 200;
                res.setHeader('Content-Type', 'application/json');
                return res.json(favs);
            }, (err) => next(err))
            .catch((err) => next(err));
        }
        else {
            var noofids = req.body.length;
            for (var i=0; i<noofids ; i++) {
                if(favs.dishes.indexOf(req.body[i]._id) > -1) {
                    return res.json('It is already in the dishes');
                }
                else {
                    favs.dishes.push(req.body[i]._id);
                    favs.save()
                    .then((doc) => {
                        Favorites.findById(doc._id)
                        .populate('User').populate('Dishes')
                        .then((fav) => {
                            res.statusCode = 200;
                            res.setHeader('Content-Type', 'application/json');
                            return res.json(fav);
                        }, (err) => next(err))
                        .catch((err) => next(err));
                    }, (err) => next(err))
                    .catch((err) => next(err));
                }
            }
        }
    }, (err) => next(err))
    .catch((err) => next(err));

})