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

Asked

Viewed 956 times

2

Well, I’m a beginner in Nodejs and started studying for academic purposes. In another question I asked here at SO-BR (What is the "res.send()" command for in Express?) I asked what this command was for and it was answered very well, but the problem now is that I have no idea why to use this command and when to use it. Could you explain to me and if possible exemplify? I thank you from now on the collaboration and patience of all.

1 answer

1


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

In express it can be used to respond in a server route, as in the example below to return the server result upon that request in the URL informed using a GET request in the /user path:

1)In the main file of your app.js upload the route file to all routes from /:

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

2)In the file Routes/index.js indicate that for the route /user the server will respond with a text with the contents inside the parentheses. Also send response code 201 signaling response successfully:

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

router.get('/user', (request, response) => {
    response.status(201);
    response.send("RESPOSTA TEXTO");
});
  • Um... I think I got it a little bit. I’m going to do some research. Thank you for answering!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.