【问题标题】:Express redirect to front-end route with path使用路径快速重定向到前端路由
【发布时间】:2015-04-01 21:29:59
【问题描述】:

假设我有一个包含路由 /contact 的 SPA

对于 Express 的直接请求(即不是 index.html),我需要执行重定向。

在 Express 中,我可以这样定义这条路线:

app.use(function(req,res,next) {
    if (req.path === "/contact" ) {
        return res.redirect("/?path=" + req.path);
    }
    next();
});

这意味着,如果用户提出直接请求,他们最终会在 index.html 的地址栏中显示“domain.com/?path=contact”。然后前端可以处理路由等。

但也许有办法让用户看不到这个丑陋的网址?

编辑:在发送给用户的 HTTP 标头中包含此路径信息是否可以接受?

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    我找到了发送 index.html 文件作为响应的解决方案。这样地址栏永远不会改变。

    app.use(function(req,res,next) {
        if (req.path === "/contact" ) {
            res.sendFile(...);
            return;
        }
        next();
    });
    

    【讨论】:

    • 是的,这个解决方案是可以接受的,而不是问题中的那个。虽然,您可能希望使用模板引擎 (express-hbs) 来简化事情。然后你可以调用 ``` res->render('
    猜你喜欢
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 2015-09-07
    相关资源
    最近更新 更多