Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 817
miniml Avatar asked Oct 12 '15 18:10

miniml


People also ask

What is RES and REQ in Express?

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.

How does Express work?

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.

What is RES on Express?

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.

What is Express () in node JS?

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.


1 Answers

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.

like image 70
joews Avatar answered Sep 26 '22 13:09

joews