const express = require("express")
const app = express();
app.listen(3000);
console.log("服务器启动,端口3000......");
get("/路由名",callback)
app.get("/",(req,res)=>{
res.send("hi")
})
next参数:get(路径,callback,next)
当有next参数时,路径在匹配到处理函数并处理后会继续向后匹配
app.get("/a",(req,res,next)=>{
req.name = "Asia"
next();
})app.get("/a",(req,res)=>{
res.send(req.name);
})
const express = require("express")
const app = express();
const home = express.Router();
app.use("/home",home);home.get("/a",(req,res)=>{
res.send("aaaa")
})home.get("/b",(req,res)=>{
res.send("bbbb")
})app.listen(3000);
console.log("服务器启动,端口3000......");
请求路径:http://localhost:3000/index?name=Asia&age=13
const express = require("express")
const app = express();
app.get('/index',(req,res)=>{
res.send(req.query);//{"name":"Asia","age":"13"}})
app.listen(3000);
console.log("服务器启动,端口3000......");
Express中接收post请求参数需要借助第三方包body-parser
js文件
const express = require("express");
const bodyParser = require('body-parser');const app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.post('/add',(req,res)=>{
res.send(req.body)
})app.listen(3000);
console.log("服务器启动,端口3000......");
htmlpost请求文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form action="http://localhost:3000/add"
method="post">
<input type="text" name="Asia"/>
<input type="submit" name=""/>
</form>
</body>
</html>
浏览器请求路径:http://localhost:3000/add
结果:{"Asia":"Asiaaaaa"}
const express = require("express");
const app = express();
app.get('/find/:id',(req,res)=>{
res.send(req.params)
})app.listen(3000);
console.log("服务器启动,端口3000......");