Why do we add properties to request object? - node.js

I can't understand why do we add properties to request object?
As I know, the request object comes from the front end side and if any information is needed or they have, the frontend side should attach it to the request object and send it to backend side like a cookie or JWT token, etc.
And after we got that information in the backend side we can add/update more properties to the response object, like new JWT token, new session ID, etc.
But I see in backend codes, they also add properties to request object and this is vague to me. I don't know why the backend side should add something to the request? Maybe because of the internal transactions between the different middleware this happens? I mean middleware1 adds something to the request object and sends it to the middleware2 in backend side?
For example I can't understand why do we add something to req.session not res.session? Because as I understand this data should be passed to the frontend side to be added into their next request.
But if there is any other reason for adding properties to req object instead of the res object, please let me know?

Mutating the request object by adding additional properties is the primary method of passing additional data between middlewares within Express. Since the request and response are passed to every middleware, this is the only chain that gives you continuity between middlewares.
(You will also see some passed on the response object as well, but in general it's most common to see it on req).
Note that you need to avoid collisions with Express's properties and methods as well as the underlying connection objects from Node.

Related

Why do we need to add .end() to a response?

Currently building a RESTful API with express on my web server, and some routes like the delete route for a document with mongoose ex. await Note.findByIdAndRemove(request.params.id) response.status(204).end() send response statuses with end()
Why do I need to add the .end()? What in these cases, and why cant one just send response.status(204)
With some responses that return json, the response.status(201).json works fine
Only certain methods with Express or the http interface will send the response. Some methods such as .status() or .append() or .cookie() only set state on the outgoing response that will be used when the response is actually sent - they don't actually send the response itself. So, when using those methods, you have to follow them with some method that actually sends the response such as .end().
In your specific example of:
response.status(204)
You can use the Express version that actually sends the response:
response.sendStatus(204)
If you choose to use .status() instead, then from the Express documentation, you have to follow it with some other method that causes the response to be sent. Here are examples from the Express documentation for .status():
res.status(403).end()
res.status(400).send('Bad Request')
res.status(404).sendFile('/absolute/path/to/404.png')
Since all three of these other methods will cause the response to be sent and when the response goes out, it will pick up the previously set status.

Nest.js API endpoint for validating the POST data

I want to validate the entity data separately from making a POST request and display errors in the form. I'm using class-transformer. What's the best way to achieve this with Nest?
Sounds exactly like what the ValidationPipe is for. You decorate your DTO with class-validator decorators, set the #Body() type in your endpoint, and bind the pipe and viola, the request gets validated when sent to the server and returns errors that you can parse if any exist

Node.js: is request unique?

In node.js, when using https-module and createserver. When user makes request to httpsserver, is request unique or can different request has same request (id?). If it is unique, which property should be to use?
The request argument in an http request handler is a Javascript object and every one is unique. They are never reused. That object is documented here.
There is no such thing as a request ID in the node.js http library. If you want to make your own request ID, you can do that yourself by just assigning a symbol as a property of the request object. You can pick any property name to use that does not conflict with existing properties.
Since this is a bit of an unusual request, I'd ask you why you're trying to do this because there may be a better way to solve your problem than trying to make a request ID. If you show your actual code and what you're trying to do, we could probably help you more specifically.
If you were using Express, you could set your own request ID with some middleware like this:
// set request ID
let reqCntr = 0;
app.use((req, res, next) => {
req._localID = reqCntr++;
next();
});
Just place this middleware before any other request handlers that wish to use the id. You can pick any non-conflicting property name. I picked _localID.

How to send a http response using koajs

I'm trying to validate a webhook via facebook. So facebook hits my url my-url/facebook/receive within my route in nodejs i'd do res.send(req.query['hub.challenge']); to send an http response.
I'm using KoaJS. From what i understand, Koajs merges the request and response object into ctx but when reading through the docs I can't find anything along the lines of ctx.send or similar to send a http response.
Can anyone give me some direction or links.
Thanks.
To send the body of a response, you can simply do ctx.response.body = 'Hello'. There are many aliases attached to ctx, so you don't necessarily have to reference the response or request yourself. Doing ctx.body = 'Hello' would be the same as the code above.
If you wanted to set headers, you would use the ctx.set() method. For example: ctx.set('Content-Type', 'text/plain').
To access the query parameters, you would use ctx.request.query['some-key'] (or simply the alias ctx.query['some-key']).
All of the different request/response methods are documented pretty well at the Koa website along with a list of aliases attached to ctx. I highly recommend you give it a read.

How to access a global variable on client and server in node/express?

Let's say I have a variable, x, which is set on the request req.x in an express middleware. We can expose this to client through the template, <%- window.x = req.x %>.
I would now like to use this variable globally. On client, we can use x directly since it's in the window context. But on the server, how do we do the same if there is no window or global context?
We can't set it on globals object in Node because that really global, not global to the request.
There is no such thing as global to a request. Because there can be many requests in flight at once in node.js, there is no place to store something that is global to a request other than on the request object itself.
So, the usual solution here (and the general OO way of doing things) is to just pass the request object to anything that needs request-specific state. Then those functions can access whatever state is desired on the request object.
You can manufacture some sort of global store lookup that would allow you to store something globally and then be able to look it up given some key (such as a userID for a given request or some cookie value for a given request). This is basically how persistent session data is stored. But, if you're trying to access data that is specific to a user or to a request, you're going to have to pass something along to any function that needs that info that can be used as a key to look up the right data in the global store because there can be many requests active at a time.
While node.js is largely single threaded, any time you make any sort of async call in a request handler (reading asynchronously from the disk or doing networking or setting a timer), then other requests get a chance to start running and many can be in flight at the same time. Thus, there is no way to associate generic global state with any given request.
The usual way to solve this is to just pass this state along to other functions that might need it:
app.get("somepath", function(req, res) {
callSomeFunc(req);
});
function callSomeFunc(request) {
callSomeOtherFunc(request);
}
function callSomeOtherFunc(r) {
// access request info from the r argument here
}

Resources