javascript node.js next()

后端 未结 3 577
日久生厌
日久生厌 2020-11-27 10:31

I see a lot of use next in node.js.

What is it, where does it come from? What does it do? Can I use it client side?

Sorry it\'s used for example

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 10:56

    It's basically like a callback that express.js use after a certain part of the code is executed and done, you can use it to make sure that part of code is done and what you wanna do next thing, but always be mindful you only can do one res.send in your each REST block...

    So you can do something like this as a simple next() example:

    app.get("/", (req, res, next) => {
      console.log("req:", req, "res:", res);
      res.send(["data": "whatever"]);
      next();
    },(req, res) =>
      console.log("it's all done!");
    );
    

    It's also very useful when you'd like to have a middleware in your app...

    To load the middleware function, call app.use(), specifying the middleware function. For example, the following code loads the myLogger middleware function before the route to the root path (/).

    var express = require('express');
    var app = express();
    
    var myLogger = function (req, res, next) {
      console.log('LOGGED');
      next();
    }
    
    app.use(myLogger);
    
    app.get('/', function (req, res) {
      res.send('Hello World!');
    })
    
    app.listen(3000);
    

提交回复
热议问题