Node.js:相对路径和绝对路径

时间:2016-04-22 09:49:26

标签: node.js

在提供页面时我遇到了麻烦(在我的例子中,是nodejs)。

假设我有以下网址:http://localhost:80,它提供简单的html网页,但您必须登录,无论是重定向到登录页面(http://localhost:80/login)。

这很简单,一切正常。 现在假设我有另一个网址http://otherdoamin.com/internal/back,它会在端口80上重定向到我的服务器。

我无法找到管理我的服务器以处理这两个网址的最佳方法。

这是一个代码示例,仅用于显示逻辑:

function checkAuth(req, res, next) {
 //if user isn't logged, redirect to login
}

app.get('/login', function(req, res) {
  //if user is logged, redirect to base path (/) which serves an html page
  //else
  //display login.html page
})

app.get('/', checkAuth, function (req, res) {
  res.sendFile(__dirname + '/views/index.html');
});

现在让我说我有以下情况:

我转到http://localhost:80,但我没有登录,我被重定向到登录页面(http://localhost:80/login)。登录后,我被重定向回http://localhost:80

但是如果我用我的其他URL(http://otherdoamin.com/internal/back)执行以下情况,我将遇到路径问题:如果我有绝对路径,重定向到登录将起作用,但登录后,我将重定向到http://otherdoamin.com/而不是http://otherdoamin.com/internal/back/,这很明显。

1 个答案:

答案 0 :(得分:1)

选项1:

将otherdomain.com/internal/back设置为反向代理路径定义中的基本网址。

选项2:

存储完全限定的原始请求网址:

var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;

然后使用它来重定向;