美文网首页
express中router对象

express中router对象

作者: Bigbang_boy | 来源:发表于2018-07-01 18:41 被阅读0次

express基本路由

const express = require('express')
const app = express()

app.get('/', function (req, res) {
  res.send('hello, express')
})

app.get('/users/:name', function (req, res) {
  res.send('hello, ' + req.params.name)
})

app.listen(3000)

req.query: 解析后的 url 中的querystring,如?name=hahareq.query 的值为{name: 'haha'}
req.params: 解析 url 中的占位符,如/:name,访问/hahareq.params 的值为{name: 'haha'}
req.body: 解析后请求体,需使用相关的模块,如 body-parser,请求体为{"name": "haha"},则 req.body 为 {name: 'haha'}

app.post('/',function(req,res))获得post请求
app.all('/',function(req,res))获得所有(包括get和post)请求

路径使用正则表达式

// 匹配任何路径中含有 a 的路径:
app.get(/a/, function(req, res) {
  res.send('/a/');
});
// 匹配 butterfly、dragonfly,不匹配 butterflyman、dragonfly man等
app.get(/.*fly$/, function(req, res) {
  res.send('/.*fly$/');
});

路由句柄

app.get('/example/b', function (req, res, next) {
  console.log('response will be sent by the next function ...');
  next();
}, function (req, res) {
  res.send('Hello from B!');
});

或在express.Router中使用路由句柄
routes/index.js

var express=require('express')
var router=express.Router()

router.get('/',function(req,res,next){
    //res.send('hello express')
    console.log('next1')
    next()
},function(req,res){
    console.log('next2')
    res.send('try again')
})

module.exports=router

index.js

var express=require('express')
var app=express()
var indexRouter=require('./routes/index')
var port=8000

//app.use('/',indexRouter)
//
//app.use('/users',usersRouter)

app.use('/',indexRouter)

app.listen(port)
console.log('listen at '+port)

使用回调函数数组处理路由:

var cb0 = function (req, res, next) {
  console.log('CB0');
  next();
}

var cb1 = function (req, res, next) {
  console.log('CB1');
  next();
}

var cb2 = function (req, res) {
  res.send('Hello from C!');
}

app.get('/example/c', [cb0, cb1, cb2]);

相关文章

网友评论

      本文标题:express中router对象

      本文链接:https://www.haomeiwen.com/subject/pllhuftx.html