gpt4 book ai didi

javascript - Node + Express : Does Express clone the req and res objects for each request handler?

转载 作者:搜寻专家 更新时间:2023-10-31 23:00:34 25 4
gpt4 key购买 nike

如果 Javascript 通过引用复制对象,那么 Express 是否会在将它们传递给每个请求处理程序之前克隆 reqres 对象?如果不是,那么 Express 如何处理同时运行并使用对 reqres 的相同引用的路由之间可能发生的冲突?

最佳答案

Express 不会克隆 reqres。您可以在这个示例应用中看到:

var http = require('http');
var express = require('express');

var app = express();
var testReq, testRes;

app.use(function(req, res, next) {
console.log('middleware');
testReq = req;
testRes = res;
next();
});

app.get("*", function(req,res) {
console.log('route')
console.log('req the same? ' + (req === testReq)); // logs true
console.log('res the same? ' + (res === testRes)); // logs true

res.send(200);
});


http.createServer(app).listen(8080);

curl测试:

$ curl localhost:8080

这是一个有用的特性 - 它意味着中间件函数可以使用 reqres 将数据传递给下游函数。例如,授权中间件可能会添加一个 req.user 属性。

并发性在这里不是问题,因为 Node.js 是单线程的——两条路由不可能在任何给定时间运行。

它也不会通过多个路由运行单个请求 - 您可以添加另一个 get("*") 路由,您会发现它不会被调用。

关于javascript - Node + Express : Does Express clone the req and res objects for each request handler?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33087765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com