亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

快速.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 關注
  • 125 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號