简体   繁体   English

ExpressJS 中的 app.use 函数如何重定向以“/”结尾的 url?

[英]How app.use function in ExpressJS redirects urls ending with "/"?

This code will redirect all the URLs that end with a "/" to the same URL but without the "/".此代码会将所有以“/”结尾的 URL 重定向到相同但不带“/”的 URL。 For example, if the user navigates to http://localhost:3000/about/ , they will be redirected to http://localhost:3000/about .例如,如果用户导航到http://localhost:3000/about/ ,他们将被重定向到http://localhost:3000/about This will make the image URLs and stuff in the HTML files always work correctly.这将使 HTML 文件中的图像 URL 和内容始终正常工作。

        var express = require('express');
        var app = express();
        app.use(function (req, res, next) {  
            if (req.path.substr(-1) == '/' && req.path.length > 1) {
        var query = req.url.slice(req.path.length);  
res.redirect(301, req.path.slice(0, -1) + query);
 } else {
                next();
            }
});

Can anyone explain me whats going on inside this code.谁能解释一下这段代码里面发生了什么。 In my understanding, if the requested path last index is equal to / and requested path length is greater than 1 then the below codes must be executed.根据我的理解,如果请求的路径最后一个索引等于 / 并且请求的路径长度大于 1,则必须执行以下代码。

So if the condition is met, query variable slice the requested url on the basis of the argument it receives as actual path length as requested the redirect function takes slice function as its callback function.因此,如果满足条件,则查询变量根据它收到的参数对请求的 url 进行切片,作为请求的实际路径长度,重定向函数将切片函数作为其回调函数。

The slice method has two arguments. slice 方法有两个参数。 The first argument takes first index value and -1 takes last index value.第一个参数取第一个索引值,-1 取最后一个索引值。 It also includes the result in query variable.它还包括查询变量中的结果。

The best solution would be to use this package最好的解决方案是使用这个包

$ npm install connect-slashes

https://www.npmjs.com/package/connect-slashes https://www.npmjs.com/package/connect-slashes

Then you can use as below然后你可以使用如下

var connect = require("connect")
  , slashes = require("connect-slashes");

connect()
  .use(connect.logger())
  .use(connect.static())
  .use(slashes(false))
  .listen(3000);

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

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