Node.js使用Express.Router的方法
在實際開發(fā)中通常有幾十甚至上百的路由,都寫在 index.js 既臃腫又不好維護,這時可以使用 express.Router 實現(xiàn)更優(yōu)雅的路由解決方案。
目錄結構如下:
routes的index.js代碼如下:
const express = require('express') const router = express.Router() router.get('/', function (req, res) { res.send('hello, express') }) module.exports = router
routes的users.js代碼如下:
const express = require('express') const router = express.Router() router.get('/:name', function (req, res) { res.send('hello, ' + req.params.name) }) module.exports = router
主index.js代碼如下:
const express = require('express'); const app = express() const indexRouter = require('./routes/index'); const userRouter = require('./routes/users'); app.use('/', indexRouter); app.use('/users', userRouter); app.listen(3000);
瀏覽器訪問請求:
每個路由文件通過生成一個 express.Router 實例 router 并導出,通過 app.use 掛載到不同的路徑。
在實際開發(fā)中推薦使用 express.Router 將不同的路由分離到不同的路由文件中。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- node.js中express模塊創(chuàng)建服務器和http模塊客戶端發(fā)請求
- node.js的Express服務器基本使用教程
- 零基礎搭建Node.js、Express、Ejs、Mongodb服務器及應用開發(fā)入門
- node.js Web應用框架Express入門指南
- Node.js使用Express創(chuàng)建Web項目詳細教程
- win7下安裝配置node.js+express開發(fā)環(huán)境
- Node.js Express安裝與使用教程
- Node.js+Express配置入門教程詳解
- node.js express安裝及示例網(wǎng)站搭建方法(分享)
- Node.js的Express框架使用上手指南
- node.js基于express使用websocket的方法
- Node.js創(chuàng)建一個Express服務的方法詳解
相關文章
node作為中間服務層如何發(fā)送請求(發(fā)送請求的實現(xiàn)方法詳解)
node作為中間服務層如何發(fā)送請求?下面小編就為大家分享一下發(fā)送請求的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助2018-01-01windows如何把已安裝的nodejs高版本降級為低版本(圖文教程)
這篇文章主要介紹了windows如何把已安裝的nodejs高版本降級為低版本,本文分步驟通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12Nodejs 中的 Buffer 類的創(chuàng)建與基本使用
這篇文章主要為大家介紹了Nodejs中Buffer的使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10