Why and when to use "res.send ()" in an application? NodeJS and Express

2

Well, I'm a beginner in NodeJS and I started studying for academic purposes. In another question I made here in SO-BR ( What is the command" res.send () "in Express? ) I asked what this command was for and it was answered very well, but the problem now is that I do not the least idea of why to use this command and when to use it. Could you explain and, if possible, exemplify? Thank you in advance for your cooperation and patience.

    
asked by anonymous 09.10.2017 / 01:35

1 answer

0

The res.send command is for the server to send response to the web client.

In Express it can be used to respond on a server route, as in the example below to return the server result by that request on the URL entered using a GET request in the / user path:

1) In the main file of your application app.js load the route file for all routes from /:

// router
app.use('/', require('./routes'));

2) In the routes / index.js file indicate that for the route / user the server will respond with a text with the content inside the parentheses. The response code 201 is also sent by successfully flagging the response:

const express = require('express');
const router = express.Router();

router.get('/user', (request, response) => {
    response.status(201);
    response.send("RESPOSTA TEXTO");
});
    
10.10.2017 / 17:43