When to use next() and return next() in Node.js

前端 未结 5 1992
执念已碎
执念已碎 2020-11-30 17:07

Scenario: Consider the following is the part of code from a node web app.

app.get(\'/users/:id?\', function(req, res, next){
    var id = re         


        
相关标签:
5条回答
  • 2020-11-30 17:47

    As @Laurent Perrin's answer:

    If you don't do it, you risk triggering the callback a second time later, which usually has devastating results

    I give an example here if you write middleware like this:

    app.use((req, res, next) => {
      console.log('This is a middleware')
      next()
      console.log('This is first-half middleware')
    })
    
    app.use((req, res, next) => {
      console.log('This is second middleware')
      next()
    })
    
    app.use((req, res, next) => {
      console.log('This is third middleware')
      next()
    })
    

    You will find out that the output in console is:

    This is a middleware
    This is second middleware
    This is third middleware
    This is first-half middleware
    

    That is, it runs the code below next() after all middleware function finished.

    However, if you use return next(), it will jump out the callback immediately and the code below return next() in the callback will be unreachable.

    0 讨论(0)
  • 2020-11-30 17:55

    Some people always write return next() is to ensure that the execution stops after triggering the callback.

    If you don't do it, you risk triggering the callback a second time later, which usually has devastating results. Your code is fine as it is, but I would rewrite it as:

    app.get('/users/:id?', function(req, res, next){
        var id = req.params.id;
    
        if(!id)
            return next();
    
        // do something
    });
    

    It saves me an indentation level, and when I read the code again later, I'm sure there is no way next is called twice.

    0 讨论(0)
  • 2020-11-30 17:56

    It is best not to use it at all! I explain, and that is what I do also explain it.

    The next () function that can have any name and by convention has been set to next. It is indirectly related to the operations (PUT, GET, DELETE, ...) that are generally performed on the same URI resource for example / user /: id

    app.get('/user/:id', function (req,res,next)...)
    app.put('/user/:id', function (req,res,next)...)
    app.delete('/user/:id', function (req,res,next)...)
    app.post('/user/', function ()...)
    

    Now if you look at app.get, app.put and app.delete use the same uri (/ user /: id), the only thing that differentiates them is their implementation. When the request is made (req) express puts the req first in app.get, if any validation you created because that request is not for that controller fails, it passes the req to app.put which is next route in te file and so on. As seen in the example below.

        app.get('/user/:id', function (req,res,next){
    
        if(req.method === 'GET')
        //whatever you are going to do
        else
          return next() //it passes the request to app.put
    
        //Where would GET response 404 go, here? or in the next one. 
        // Will the GET answer be handled by a PUT? Something is wrong here.
    
       })
        app.put('/user/:id', function (req,res,next){
    
        if(req.method === 'PUT')
        //whatever you are going to do
        else
          return next()
    
       })
    

    The problem lies, that in the end you end up passing the req to all the controllers hoping that there is one that does what you want, through the validation of the req. In the end all controllers end up receiving something that is not for them :(.

    So, how to avoid the problem of next ()?

    The answer is really simple.

    1-there should only be one uri to identify a resource

    http://IpServidor/colection/:resource/colection/:resource if your URI is longer than that, you should consider creating a new uri

    Example http://IpServidor/users/pepe/contacts/contacto1

    2-All operations on this resource must be done respecting the idempotence of the verbs http (get, post, put, delete, ...) so the call to a URI really only has one way of calling

    POST http://IpServidor/users/  //create a pepe user 
    GET http://IpServidor/users/pepe  //user pepe returns   
    PUT http://IpServidor/users/pepe  //update the user pepe 
    DELETE http://IpServidor/users/pepe  //remove the user pepe
    

    More info [https://docs.microsoft.com/es-es/azure/architecture/best-practices/api-design#organize-the-api-around-resources][1]

    Let's see the code! The concrete implementation that makes us avoid the use of next ()!

    In the file index.js

    //index.js the entry point to the application also caller app.js
    const express = require('express');
    const app = express();
    
    const usersRoute = require('./src/route/usersRoute.js');
    
    app.use('/users', usersRoute );
    

    In the file usersRoute.js

        //usersRoute.js
        const express = require('express');
        const router = express.Router();
    
        const getUsersController = require('../Controllers/getUsersController.js');
        const deleteUsersController = require('../Controllers/deleteUsersController.js');
    
        router.use('/:name', function (req, res) //The path is in /users/:name
        {
        switch (req.method)
        {
        case 'DELETE':
          deleteUsersController(req, res);
          break;
        case 'PUT':
         // call to putUsersController(req, res);
         break;
        case 'GET':
         getUsersController(req, res);
         break;
        default:
         res.status(400).send('Bad request');
        } });
    
    router.post('/',function (req,res) //The path is in /users/
    {
        postUsersController(req, res);
    });
    
    module.exports = router;
    

    Now the usersRoute.js file does what a file called usersRoute is expected to do, which is to manage the routes of the URI /users/

    //file getUsersController.js

    //getUsersController.js
        const findUser= require('../Aplication/findUser.js');
        const usersRepository = require('../Infraestructure/usersRepository.js');
    
        const getUsersController = async function (req, res)
        {
    
           try{
              const userName = req.params.name;
            //...
              res.status(200).send(user.propertys())
    
            }catch(findUserError){
               res.status(findUserError.code).send(findUserError.message)
            }
        }
       module.exports = getUsersController;
    

    In this way you avoid the use of next, you decouple the code, you gain in performance, you develop SOLID, you leave the door open for a possible migration to microservices and above all, it is easy to read by a programmer.

    0 讨论(0)
  • 2020-11-30 17:58

    Next() :

    Calling this function invokes the next middleware function in the app. The next() function is not a part of the Node.js or Express API, but is the third argument that is passed to the middleware function.

    0 讨论(0)
  • 2020-11-30 18:04

    next() is part of connect middleware. Callbacks for router flow doesn't care if you return anything from your functions, so return next() and next(); return; is basically the same.

    In case you want to stop the flow of functions you can use next(err) like the following

    app.get('/user/:id?', 
        function(req, res, next) { 
            console.log('function one');
            if ( !req.params.id ) 
                next('No ID'); // This will return error
            else   
                next(); // This will continue to function 2
        },
        function(req, res) { 
            console.log('function two'); 
        }
    );
    

    Pretty much next() is used for extending the middleware of your requests.

    0 讨论(0)
提交回复
热议问题