在網上找了很多人都 express路由描述都沒看懂,后面看了官網的birds案例終于搞懂了~
// app.js 首頁
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mysql = require('mysql');
const router = require('./router/index') // 引入路由
// 開啟數據庫
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'test',
multipleStatements: true, // 允許執(zhí)行多條語句
})
connection.connect(() =>{
console.log('鏈接成功')
});
app.use(bodyParser.urlencoded({
extends: true
}));
//設置跨域訪問
app.all('*', (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
// 使用路由 /index 是路由指向名稱
app.use(`/index`,router)
//配置服務端口
var server = app.listen(3000, () => {
const hostname = 'localhost';
const port = 3000;
console.log(`Server running at http://${hostname}:${port}/`);
})
新建一個路由的文件夾,并且新建一個index.js的文件

image.png
const express = require(`express`)
const router = express.Router()
router.use((req, res, next) => {
console.log(`路由執(zhí)行成功啦~~~`, Date.now());
next()
})
router.get(`/`, (req, res, next) => {
res.json({
status: 200,
data: `請求成功`
})
})
router.get(`/data`, (req, res, next) => {
res.json({
status: 200,
data: [1, 2, 3, 4, 5, 6, 7]
})
})
module.exports = router
下面可用通過請求測試路由
http://localhost:3000/index/data
或者
http://localhost:3000/index
/index/data 和 /index 兩種方法都可以訪問
大功告成啦~~~
接下來可用根據自己項目需求分出多個模塊,建立不同名稱的文件來管理不同的路由請求。