快速.js - 无法使用导出的功能设置标头

学习如何使用Mocha,Chai,Chai-HTTP插件和MongoDB与Mongoose一起使用Express进行测试。我有一个测试来专门检测MongoDB是否会发送回一个错误,因为试图使用错误值(太短)查找文档。_id


我注意到我的部分代码正在我的其他Express路由周围重复,并希望将其重用于其他路由,因此我从另一个模块中导出了它,但现在我得到了这个:


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


不知道为什么我收到此错误。如果我有相同的代码,作为导出的函数,在路由代码内部它工作正常,但导出它只是抱怨。


代码如下:


test/route/example.test.js截图


it('Bad request with a too short ID string (12 characters minimum)', () => {

    // /api/v1/example is the endpoint

    // /blah is the param

    chai.request(app).get('/api/v1/example/blah').end((err, res) => {

       // Insert all the nice assert stuff. :) 

    });

});

路由/示例.js截图


// Packages

const router = require('express').Router();


// Models (Mongoose Schemas)

const Example = require('../models/example.model');


// Helpers

const { foundMongoError } = require('../helpers/routes');


// -----Snipped-----


router.route('/:exampleId').get((req, res) => {

    // Retrieve the exampleId parameter.

    const exampleId = req.params.exampleId;


    Example.findById(exampleId, (mongoError, mongoResponse) => {

        foundMongoError(mongoError, res); // Having an issue


        // If I have the same code that makes up foundMongoError inside here, no issues, 

        // but it will no longer be DRY.


        // Check if any responses from MongoDB

        if(mongoResponse) {

            res.status(200).json(mongoResponse);

        } else {

            return res.status(404).json({

                errorCode: 404,

                errorCodeMessage: 'Not Found',

                errorMessage: `Unable to find example with id: ${exampleId}.`

            });

        }

    });

});

助手/路线.js


const foundMongoError = (mongoError, res) => {

    if(mongoError) {

        return res.status(400).json({

            errorCode: 400,

            errorCodeMessage: 'Bad Request',

            errorMessage: mongoError.message

        });

    }

};


module.exports = {

    foundMongoError

};


HUX布斯
浏览 91回答 1
1回答

达令说

这只意味着您发送并回复了两次。您第一次将其寄回此处时:res    if(mongoError) {        return res.status(400).json({            errorCode: 400,            errorCodeMessage: 'Bad Request',            errorMessage: mongoError.message        });    }您发回了响应,但函数仍在继续工作,这意味着该函数将一直运行到此处:    if(mongoResponse) {        res.status(200).json(mongoResponse);    } else {        return res.status(404).json({            errorCode: 404,            errorCodeMessage: 'Not Found',            errorMessage: `Unable to find example with id: ${exampleId}.`        });    }这里发生第二个响应,这里你得到错误。我会这样重写代码:您不是返回响应,而是返回一个表示存在错误,否则:truefalseconst foundMongoError = (mongoError, res) => {    if(mongoError) {        res.status(400).json({            errorCode: 400,            errorCodeMessage: 'Bad Request',            errorMessage: mongoError.message        });    return true;    }    return false;};module.exports = {    foundMongoError};然后你可以这样写:if(foundMongoError(mongoError, res)) return;将停止函数以执行其余代码return
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript