如何呈现键值并重定向?

时间:2018-09-25 11:51:05

标签: node.js express express-handlebars

给出的是:

    router.get('/register', function(req, res, next) {
        var message = "";
        res.render('register', { title: 'Register', userMessage: message});

    });

    router.post('/registration/submit', function(req, res, next) {
            // ##### Some unintersting code is here ########## (....) -->
            var message = "";
            MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {

            const db = client.db(dbName);
            db.collection('userdata').findOne({ email: mailAddress }, (error, result) => {
                if (!error) {
                    if (result) {
                        console.log("Item exists");
                        message = 'User already exists!';
                    } else {
                        db.collection('userdata').insertOne(item, (err, result) => {
                            assert.equal(null, err);
                            console.log("Item inserted:");
                            message = "User inserted! <br>You entered: " + item.email + " as your emailaddress.";
                            console.log(item);
                            client.close();
                        }); 
                    }
               } else {
                    message = "Unexected error with DB";
                    console.log("MongoDB error");
               }
            });

        });
        res.redirect('/register', {userMessage: message} );
    });

register.html:

<form action="/registration/submit" method="post" style="margin:20px">

    {{#if userMessage}}
        {{message}}
    {{/if}}


    <!-- ... SOME UNINTERESTING CODE (input-fields) -->
    <button class="btn btn-primary" id="regBut" type="submit">Register</button>
</form>

单击“提交”按钮后,将检查项目是否已存在。之后,应该显示一个message。这样,控制台会引发一些错误:

表达已弃用的res.redirect(URL,status):使用res.redirect(status,url)代替route \ index.js:149:7 POST /注册/提交 '抛出新的错误('发送头后不能设置头'。) 错误:发送标头后无法设置标头。”

正在使用模板引擎车把。如何像res.redirect('/register', {userMessage: message} );那样进行渲染和重定向以显示来自<form action='/registration/submit'>的消息?

0 个答案:

没有答案