node.js 如何在快递中设置默认路径(路由前缀)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29993660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:42:27 来源:igfitidea点击:
How to set default path (route prefix) in express?
提问by boop
Instead of doing path + '..'foreach route - how can I prefix every route?
而不是做path + '..'foreach 路由 - 我如何为每条路由添加前缀?
My route shall be
我的路线是
/api/v1/user
What I don't want to do
我不想做的事
var path = '/api/v1';
app.use(path + '/user', user);
What I want to do
我想做的事
var app = express();
app.setPath('/api/v1');
app.use(..);
回答by Explosion Pills
回答by Andrew Chudinovskyh
If you are using Express 4 Routeryou can use route() method to set the path and create a chainable route handler
如果您使用的是 Express 4,Router您可以使用 route() 方法来设置路径并创建一个可链接的路由处理程序
app.route('/book')
.get(function (req, res) {
res.send('Get a random book')
})
.post(function (req, res) {
res.send('Add a book')
})
.put(function (req, res) {
res.send('Update the book')
});

