Express.js-无法使用导出的功能设置标题

问题描述 投票:0回答:1

了解如何使用MochaChaiChai-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 Snippit

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. :) 
    });
});

route / example.js Snippit

// 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}.`
            });
        }
    });
});

helpers / routes.js

const foundMongoError = (mongoError, res) => {
    if(mongoError) {
        return res.status(400).json({
            errorCode: 400,
            errorCodeMessage: 'Bad Request',
            errorMessage: mongoError.message
        });
    }
};

module.exports = {
    foundMongoError
};
javascript node.js express mongoose mocha
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}.`
        });
    }

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

我会这样重写代码:

而不是返回响应,而是返回true,这意味着存在错误,否则返回false

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;

将停止该函数执行其余代码

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.