加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Node.js使用Express.Router的方法

发布时间:2020-12-16 08:17:08 所属栏目:百科 来源:网络整理
导读:在实际开发中通常有几十甚至上百的路由,都写在 index.js 既臃肿又不好维护,这时可以使用 express.Router 实现更优雅的路由解决方案。 目录结构如下: routes的index.js代码如下: router.get('/',function (req,res) { res.send('hello,express') }) modul

在实际开发中通常有几十甚至上百的路由,都写在 index.js 既臃肿又不好维护,这时可以使用 express.Router 实现更优雅的路由解决方案。

目录结构如下:

routes的index.js代码如下:

router.get('/',function (req,res) {
res.send('hello,express')
})

module.exports = router

routes的users.js代码如下:

router.get('/:name',' + req.params.name)
})

module.exports = router

主index.js代码如下:

app.use('/',indexRouter);
app.use('/users',userRouter);

app.listen(3000);

浏览器访问请求:

每个路由文件通过生成一个 express.Router 实例 router 并导出,通过 app.use 挂载到不同的路径。

在实际开发中推荐使用 express.Router 将不同的路由分离到不同的路由文件中。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读