search

Home  >  Q&A  >  body text

node.js - When router.get("conten1") is used twice, an error is reported. please help

image description

Result1 directly reports an error, please help

给我你的怀抱给我你的怀抱2821 days ago723

reply all(1)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-05-24 11:40:38

    Why

    1. When the first get route is parsed successfully, the server will render content1 directly without waiting for the second one. This is why there is a next in the parameter.

    2. In express, the order of routes is next to each other. If you do not use next, then only the callback method in the first get() will be triggered by default.

    Solution

    Synchronize query and finally render together

    I am also a novice, I wrote some code for you to explain the logic problem

    
    let data = {};
    router.get('/', function (req, res, next) {
        data = {};
        //模拟DB查询回调
        setTimeout(function () {
            data.user = {id: 1, username: 'zhaojunlike'};
            //传递到下面
            next();
        }, 1000);
    
    });
    router.get('/', function (req, res, next) {
        console.log(data);
        //模拟第二次查询并且输出Render
        setTimeout(function () {
            data.content = {email: 'zhaojunlike@gmail.com'};
            res.render('index', {title: 'Express', data: data});
        }, 1000);
    
    });
    

    reply
    0
  • Cancelreply