【问题标题】:How to make a redirection to a Jade/Pug file within a MongoDB callback?如何在 MongoDB 回调中重定向到 Jade/Pug 文件?
【发布时间】:2016-12-22 18:11:47
【问题描述】:

如果在连接数据库时出现错误,我想在函数 express().get(或等效的函数)之外和 MongoDB 的函数 connect 内使用 Express 函数 redirect

这个重定向的目的地是一个 Jade/Pug 文件,这就是为什么我必须使用 Pug 的函数 render

我的问题是:例如,我如何使用redirect 来做到这一点?确实,我没有对象res,因为我不使用函数express().get

这是我写的代码;一定要实现,但我不知道怎么实现。

const express = require('express');
const app = express();
const mongo_client = require('mongodb').MongoClient;
mongo_client.connect("mongodb://localhost:27016/my_db", (error, database) => {
        if(error) { // If an error has been raised while connecting to the database
            app.locals.error = error;
            app.render('db_error.jade', (error, rendered) => { // We generate the HTML code and pass it to a redirection
                // But how ???
                if(error) {
                    throw error;
                }
            });
            throw error;
        }

【问题讨论】:

    标签: node.js mongodb express redirect pug


    【解决方案1】:

    更重要的是,您没有请求,因为它不在路由中。不仅没有什么可以让您做出回应,而且没有人要求您首先做出回应。这一切都发生在任何人的网络浏览器参与之前。

    如果您想在数据库关闭时显示页面,您需要在所有请求中使用middleware 以查看应用是否已连接到 Mongo 并在必要时重定向到您的错误页面。

    【讨论】:

      猜你喜欢
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      相关资源
      最近更新 更多