Where does .send() come from?


Where does .send() come from?


.send() is an express specific method from the response object.
With express, we can create servers and APIs, so when we talk about requests, 99% of the time we are referring to queries that our own server/API is receiving, not a query that we are sending to another site. Since then we are working with our own internal process, the express library facilitates how we can submit responses by providing a response object, commonly seen as: res, and it represents the HTTP response that we will emit when we receive an HTTP request to any of our endpoints.

The object itself contains a series of helpful methods that can help us deliver a proper response, two of the most commonly used are .send() which takes the data passed to it and structures it as the body content of the response while taking care of common information about the response, like count and content type. Another commonly used is .json() which simply returns the data passed to it as a JSON object with the proper content type as "json" and not "text/html" or “application/octet-stream”, .json() can be very helpful in moments when consistency is key.

to have a better idea of the request object and .send(), we can use our exercise, there we have a get request:

app.get('/expressions', (req, res, next) => {

this will be received at the endpoint /expressions, because of express, that .get() method already knows to pass the request it is receiving, the response object from express, and the next method that its simple purpose is to skip to the next action or function. so our get request would look kind of like this when it receives the request:

app.get('/expressions', ({...}, {...}, next)=>{

the first object is the request object that will have information on where it comes from, the content if there is any data being passed, the time, the connection, if it is readable, in short express also has a request object that is passed to the callback function with the data collected from the query received to our /expressions endpoint. then our response object is very alike, it also contains if it is readable, what the query was, what method was used, what url did the request come through, and when we give it:


the object of expressions is attached as a body:

body: [...]

and that body is the main thing returned to the user:

"id": 1,
"emoji": "😀",
"name": "happy"
"id": 2,
"emoji": "😎",
"name": "shades"
"id": 3,
"emoji": "😴",
"name": "sleepy"