Express middleware for people who are anal about trailing slashes.
If you're a good person, then you enable Express' 如果您是一个好人,那么您可以启用Express的“严格路由”,因为您了解"strict routing"
because you understand the difference between /about
and /about/
. /about
和/about/
之间的区别。You know that these URLs are not the same and they have different meanings. 你知道这些URL是不一样的,它们有不同的含义。The trouble is, being a good person and caring about your trailing slashes is harder than not. 问题是,做一个好人,关心你的后遗症比不关心要困难得多。Plus, you also care about other people, and it would be rude to 404 them when they forget the trailing slash. 另外,你还关心其他人,如果他们忘记了尾随斜杠,那么用404来称呼他们是不礼貌的。Luckily, there's this package to solve all your trailing slash problems :D幸运的是,有这个软件包可以解决所有的尾部斜杠问题:D
This Express middleware should come after your app's 此Express中间件应位于应用程序的router
middleware.router
中间件之后。
It will handle [GET and HEAD] requests for URLs which did not have a matching route by either adding or removing a trailing slash to the URL's path, then checking the app's router for a matching route for the new URL, in which case it will redirect the client (301 by default) to that URL.它将通过在URL路径上添加或删除尾随斜杠,然后检查应用程序的路由器是否有新URL的匹配路由,来处理没有匹配路由的URL的[GET and HEAD]请求,在这种情况下,它会将客户端(默认情况下为301)重定向到该URL。
Note: Choose the correct version of this package for your Express version:注意:请为您的Express版本选择此软件包的正确版本:
v1.x
: Express 3.xv2.x
: Express 4.xInstall using npm:使用npm安装:
$ npm install express-slash
Enable Express' 启用Express的“严格路由”设置,并在应用程序的"strict routing"
setting, and add this middleware after your app's router
middleware:router
中间件之后添加此中间件:
var express = require('express'),
slash = require('express-slash');
var app = express();
// Because you're the type of developer who cares about this sort of thing!因为你是那种关心这类事情的开发人员!
app.enable('strict routing');
// Create the router using the same routing options as the app.使用与应用程序相同的路由选项创建路由器。
var router = express.Router({
caseSensitive: app.get('case sensitive routing'),
strict : app.get('strict routing')
});
// Add the `slash()` middleware after your app's `router`, optionally specify在应用程序的“路由器”之后添加`slash()`中间件,可以选择指定
// an HTTP status code to use when redirecting (defaults to 301).重定向时使用的HTTP状态代码(默认为301)。
app.use(router);
app.use(slash());
router.get('/', function (req, res) {
res.send('Home');
});
router.get('/about/', function (req, res) {
res.send('About');
});
router.get('/about/people', function (req, res) {
res.send('People');
});
app.listen(3000);
Now when someone navigates to 现在,当某人导航到/about
, they'll be redirected to /about/
, and when someone navigates to /about/people/
, they'll be redirected to /about/people
./about
时,他们将被重定向到/about/
,当某人导航到/about/people/
,他们将被重定向到/about/people
。
This software is free to use under the MIT license. See the LICENSE file for license text and copyright information.