简体   繁体   English

Node.js重定向有/无尾随斜杠

[英]Node.js redirect with/without trailing slash

I have a javascript that does different things depending on the URL. 我有一个javascript根据URL做不同的事情。 for that to work, i need to have consistent URIs. 为了工作,我需要有一致的URI。

for example, i need users to always be on www.site.com/users/bob/ instead of www.site.com/users/bob 例如,我需要用户始终在www.site.com/users/bob/而不是www.site.com/users/bob

node unfortunately doesn't support that, as it seems. 不幸的是,节点似乎不支持它。

i tried redirecting with 我尝试重定向

router.get('/:user', function(req, res) {
    res.redirect('/users/' + req.params.user' + '/');
});

but it just results in a redirect loop, as the URL with and without slash seem to be treated as the same. 但它只会导致重定向循环,因为带有和不带斜杠的URL似乎都被视为相同。

how can i do this? 我怎样才能做到这一点? thanks! 谢谢!

edit: 编辑:

i want to route from WITHOUT slash to WITH slash. 我想从WITHOUT斜线路由到斜线。 the answers in the other question address the other way around. 另一个问题的答案解决了另一种方式。 i can't .substr(-1) my URLs 我不能.substr(-1)我的网址

In case someone else is looking for a quick zero dependency solution, this worked fine for me: 如果其他人正在寻找快速零依赖解决方案,这对我来说很好:

app.get('/:page', function(req, res){
  // Redirect if no slash at the end
  if (!req.url.endsWith('/')) {
    res.redirect(301, req.url + '/')
  }

  // Normal response goes here
});

You can get this by using third-party library which is called express-slash . 您可以使用名为express-slash的第三方库来实现此目的。 All you need to do is, 你需要做的就是,

First, install the library 首先,安装库

$ npm install express-slash

And, add these to your app.js. 并将这些添加到您的app.js.

var slash   = require('express-slash');

app.use(slash()); // set slash middleware

Then, this is your router. 然后,这是你的路由器。

router.get('/:user/', function(req, res) {
    // do your stuff
});

Hope it will be useful for you. 希望它对你有用。

Set this use after the 'express.static' use and before other use methods. 在“express.static” use和其他use方法之前设置此use

This code removes the slash from the end of path if it exists, and redirects to the new URL. 此代码从路径末尾删除斜杠(如果存在),并重定向到新URL。

If you what to add a slash you can change it so that it adds a slash if the original path doesn't have one. 如果要添加斜杠,可以更改斜杠,以便在原始路径没有斜杠的情况下添加斜杠。

app.use((req, res, next) => {
    let url = parseURL(req.url),
        pathname = url.pathname,
        search = url.search || '',
        hasSlash = pathname.charAt(pathname.length - 1) === '/';

    if (hasSlash && pathname !== '/') {
        // remove slash
        pathname = pathname.slice(0, -1);
        // redirect to truest url
        res.redirect(301, pathname + search);
    } else {
        return next();
    }
});

I'm adding this answer as a full solution that redirects non-slash routes to end with a slash. 我将这个答案添加为一个完整的解决方案,将非斜杠路由重定向到以斜杠结尾。

Firstly, enable a strict router (v4+) to disable the auto normalisation. 首先,启用严格路由器(v4 +)以禁用自动规范化。

express.Router({strict: true});

Then start your router with a catch-all route which detects if it doesn't end with a slash - and in this case also omits anything with a (.) - so images etc aren't caught. 然后用一个catch-all路由启动你的路由器,它检测它是否以斜杠结尾 - 在这种情况下也省略了带(。)的任何东西 - 所以不会捕获图像等。

var url = require('url');
router.all(/^[^.]*[^\/]$/, function(req, res) {
    let u = url.parse(req.originalUrl);
    return res.redirect(301, u.pathname + '/' + (u.search || ''));
});

This works with query string parameters etc. 这适用于查询字符串参数等。

You could try jncraton's answer , but only append slashes to directories.. 您可以尝试jncraton的答案 ,但只是在目录中添加斜杠..

const path = require('path')

app.get('/*', function(req, res) {
    if (!req.url.endsWith('/') && !path.extname(req.url)) {
        res.redirect(301, req.url + '/')
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM