首页 > 解决方案 > nodejs拦截具有多个功能的发送功能

问题描述

我尝试创建一个简单的拦截器来在所有中间件中注入一个 console.log。但是当我在路线内定义多个函数时,我遇到了问题。

const express = require('express');
const  moment = require('moment');
require('dotenv').config();
const app = express();

const config = {
    PORT: process.env.PORT,
    ENV: process.env.ENV,
    STATIC: process.env.STATIC,
    LABEL: (req)=>`${req.method} ${req.url} request timing`
}

//intercptor
const interceptor = function (...callback){
 return (req,res,next)=>{
     console.log(`info res.headersSent `,res.headersSent);
    const oldSend = res.send;
    res.send = function(data){
        console.log('SEND->',res.headersSent);
        oldSend.apply(res, arguments);

        console.timeEnd(config.LABEL(req));
        console.log(`INFO res.headersSent `,res.headersSent);
    }
    for(let i = 0 ; i<callback.length;i++){
        console.log(`res.headersSent [${i}]`,res.headersSent);
        console.log(">>>>>>>>>>>>>>>>>>>>>>>>>> execute")
        callback[i](req,res,next);
        if (res.headersSent) {
            console.log(`NOT EXEC!! res.headersSent [${i}]`,res.headersSent);
            return;
        }

    }

};
};


app.get('/example',interceptor(
 (req, res, next)=>{console.log('Hello from example 1!');next();},
         (req, res, next)=>{res.send('Hello from example 4!');},
))

app.post('/example',route(function (req, res, next){
console.log('this is example 1-B');
res.send('Hello from example 1-B!');
}))

当我在邮递员中发送请求时,我收到“来自示例 4 的您好!” 在屏幕上,但我的服务器出现故障。

服务器控制台

**************************************************
                 CONFIGURATION
 PORT: 3001
 ENV: development
 STATIC: /public
 LABEL: (req)=>`${req.method} ${req.url} request timing`
**************************************************
info res.headersSent  false
res.headersSent [0] false
>>>>>>>>>>>>>>>>>>>>>>>>>>eseguo
Hello from example 1!
res.headersSent [1] false
>>>>>>>>>>>>>>>>>>>>>>>>>>eseguo
SEND-> false
GET /example?a=1 request timing: 32.235ms
INFO res.headersSent  true
NON ESEGUO res.headersSent [1] true
_http_outgoing.js:470
    throw new ERR_HTTP_HEADERS_SENT('set');
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at Array.write (C:\xampp\htdocs\node-server\node_modules\finalhandler\index.js:285:9)
    at listener (C:\xampp\htdocs\node-server\node_modules\on-finished\index.js:169:15)
    at onFinish (C:\xampp\htdocs\node-server\node_modules\on-finished\index.js:100:5)
    at callback (C:\xampp\htdocs\node-server\node_modules\ee-first\index.js:55:10)
    at IncomingMessage.onevent (C:\xampp\htdocs\node-server\node_modules\ee-first\index.js:93:5)
    at IncomingMessage.emit (events.js:203:15)
    at endReadableNT (_stream_readable.js:1145:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)
Waiting for the debugger to disconnect...
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-server-test@1.0.0 start: `node index.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-server-test@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
Waiting for the debugger to disconnect...

Process finished with exit code 1

如果我只使用中间件中的一个功能,所有的工作

标签: javascriptnode.jsexpress

解决方案


我的错误!

const InterceptorSend=function(req, res, next) {
    var oldSend = res.send;

    res.send = function(data){
        oldSend.apply(res, arguments);
        console.timeEnd(config.LABEL(req));
    }
    next();
}
    app.use(InterceptorSend);
app.get('/example',
     (req, res, next)=>{console.log('Step 1');next();},
             (req, res, next)=>{console.log('Step 2');res.send('Hello from example 2');},
             (req, res, next)=>{console.log('Step 3');res.send('Hello from example 2B');}
    )    


推荐阅读