Node Express 中间件如何发送 res, req 对象

Node Express Middleware how to send the res, req object

我无法在函数之间发送 res(请求对象)。以下代码由我的 app.js (主要的 express 中间件)执行:

//app.js calls File.js

//File1.js 
var file2 = require('./File2.js);
export.modules = function (req,res,next) { 
    file2(data) {
        res.send(data); //<-- this is not working
    }
} 

//File2.js
export.modules = function(data){
    data = 'test';
}

我也不明白什么时候用next()或者什么时候用res.end()

从你的代码片段中很难理解,所以我将解决你关于 next 与 send 的第二个问题

你在你的中间件中使用 next,这意味着你还不想用数据响应你的客户端,但你想处理来自另一个中间件的数据,当你到达你需要使用的最终中间件时res.send();

请注意,您不能多次使用res.send,因此您必须在完成处理并要将数据响应给用户时调用它。

你必须使用 express 的中间件如下:

var app = express();
app.use(function(req,res, next){
   // some proccessing
   req.proccessData = "12312312";
   next();
})

app.use(function(req,res, next){
   // here you respond the data to the client
   res.send(req.proccessData);
})

您也可以将其与路由(get、post 等...)一起使用,当您想将数据发送到下一阶段时,只需将 next 作为第三个参数添加到路由中即可