前言
我是歌谣 微信公众号关注前端小歌谣一起学习前端知识 今天继续给大家讲解获取express获取请求采参数的讲解
案例
index.js
const express = require("express")
const app = express()
const IndexRouter=require("./router/indexRouter")
//应用
app.use(function(req,res,next){
console.log("验证token")
next()
})
app.use(function(req,res,next){
console.log("验证token")
next()
})
app.use("/",IndexRouter)
app.use((req,res)=>{
res.status(404).send("丢了")
})
app.listen(3000, () => {
console.log("server start")
})
indexRouter.js
const express = require("express")
const router = express.Router()
router.get("/home",(req,res)=>{
res.send("home")
})
router.get("/login",(req,res)=>{
console.log(req.query,"data is")
res.send("login")
})
module.exports=router
运行结果
优化
index.js
const express = require("express")
const app = express()
app.get("/", (req, res) => {
res.send("hello world
")
})
app.get("/login", (req, res) => {
res.send("hello login")
})
const func1 = (req, res, next) => {
console.log("我是歌谣")
res.send("hello home")
next()
}
app.use(func1)
app.get("/abc/:id/", (req, res) => {
res.send("hello abc")
})
app.get(/.*fly$/, (req, res) => {
res.send("hello fly")
})
app.get("/home", [func1, func2])
app.listen(3000, () => {
console.log("server start")
})
function func2(req, res, next) {
res.send({ list: [1, 2, 3] })
}
indexRoute.js
const express = require("express")
const router = express.Router()
router.get("/login",(req,res)=>{服务器托管网
res.send("ge服务器托管网t-success")
})
router.post("/home",(req,res)=>{
console.log(req.body)
res.send({ok:"1"})
})
module.exports=router
运行结果
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.fwqtg.net