为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

HUX布斯 2022-09-02 21:02:09
学习如何使用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截图// Packagesconst router = require('express').Router();// Models (Mongoose Schemas)const Example = require('../models/example.model');// Helpersconst { 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}.`            });        }    });});助手/路线.jsconst foundMongoError = (mongoError, res) => {    if(mongoError) {        return res.status(400).json({            errorCode: 400,            errorCodeMessage: 'Bad Request',            errorMessage: mongoError.message        });    }};module.exports = {    foundMongoError};
查看完整描述

1 回答

?
达令说

TA贡献1821条经验 获得超6个赞

这只意味着您发送并回复了两次。您第一次将其寄回此处时: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}.`

        });

    }

这里发生第二个响应,这里你得到错误。


我会这样重写代码:


您不是返回响应,而是返回一个表示存在错误,否则:truefalse


const 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


查看完整回答
反对 回复 2022-09-02
  • 1 回答
  • 0 关注
  • 90 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信