路由:路由是指如何定义应用的端点(URls)以及如何响应客户端的请求。Routing refers to how an application’s endpoints (URIs) respond to client requests.
controller :控制器
action :一个 controller 对应多个 action
一、一旦向客户端发送数据之后,就不能再发送数据了
const express = require("express");
const app = express();
app.get('/index/b',
(req, res, next) => {
console.log("res will be sent by the next func");
next();
},
(req, res,next) => {
res.send("Hello from B!");
next();
},
(req, res) => {
console.log("我是结尾"); // 有值
res.send("我是结尾"); // 报错
// node 的代码可以实行,但是向客户端发送的代码不会执行(报错)
});
app.listen(8080, () => {
console.log("服务已启动")
});
二、可以用中括号合并函数
const express = require("express");
const app = express();
const cb0 = (req, res, next) => {
console.log("cb0");
next();
};
const cb1 = (req, res, next) => {
console.log("cb1");
next();
};
app.get('/index/d',
[cb0, cb1],
(req, res, next) => {
console.log("res will be sent by the next func");
next();
}, (req, res, next) => {
res.send("Hello from D!");
});
app.listen(8080, () => {
console.log("服务已启动")
});
三、必经之路 ' * '
const express = require("express");
const app = express();
app.get('*',(req,res,next)=>{
console.log("必经之路!");
next(); // 一定要有
});
app.get('/index',(req,res)=>{
res.send("index");
});
app.get('/go',(req,res)=>{
res.send("go");
});
app.listen(8080, () => {
console.log("服务已启动")
});
如果用上中间件的话,把
app.get('*',(req,res,next)=>{
console.log("必经之路!");
next(); // 一定要有
});
换成
app.use((req,res,next)=>{
console.log("必经之路!");
next(); // 一定要有
});
当然,也可用 min-app
const router = express.Router();
和app的用法一样,只不过只能是 use 、 get 、 post ......那几个方法