If Javascript copies objects by reference, then does Express clone the req
and res
objects before passing them down to each request handler? If not, then how does Express handle possible conflicts between routes running simultaneously and using the same reference to req
and res
?
The req object represents the HTTP request and has properties for the request query string, parameters, body, and HTTP headers. The res object represents the HTTP response that an Express app sends when it gets an HTTP request.
Express provides methods to specify what function is called for a particular HTTP verb ( GET , POST , SET , etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response.
Short for response , the res object is one half of the request and response cycle to send data from the server to the client-side through HTTP requests.
Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application. It's a layer built on the top of the Node js that helps manage servers and routes.
Express doesn't clone req
and res
. You can see that in this example app:
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);
Test with curl
:
$ curl localhost:8080
This is a useful feature - it means that middleware functions can use req
and res
to pass data to downstream functions. For example an authorisation middleware might add a req.user
property.
Concurrency isn't a concern here because Node.js is single threaded - it is not possible for two routes to run at any given time.
It also doesn't run a single request through multiple routes - you can add another get("*")
route and you'll see that it won't get called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With