美文网首页
req.xxx API 讲解

req.xxx API 讲解

作者: kzc爱吃梨 | 来源:发表于2022-02-22 21:49 被阅读0次

request.xxx

概况:共28个API
需要特别学习的API

  • req.params
//  localhost:3000/user/1
app.get('/user/:id', (request, response, next)=> {
    console.log('request.params')
    console.log(request.params);
})
image.png
  • req.query
//  localhost:3000/user/1?name=kong&age=18
app.get('/user/:id', (request, response, next)=> {
    console.log('request.params')
    console.log(request.params);
})
image.png
  • req.get('Content-Type')
  • req.param('name')
//  localhost:3000/user/1?name=kong&age=18 
//  localhost:3000/user/kong

app.get('/user/:name', (request, response, next)=> {
    console.log('request.param')
    console.log(request.param('name'));
    next()
})
image.png

单词记忆

image.png

response.xxx

概况:共24个API
需要特别学习的API

  • res.send() / res.sendFile()
  • res.render()/res.download()
  • res.headersSent
  • res.status()
  • res.set()/ res.get()
app.get('/test', (request, response, next)=> {
    response.set('X-Kong', '123')
    response.append('X-Kong1', '456')
    response.status(401)
    response.send('hi')
    next()
})
image.png
  • res.format()
res.format({
  'text/plain': function () {
    res.send('hey')
  },

  'text/html': function () {
    res.send('<p>hey</p>')
  },

  'application/json': function () {
    res.send({ message: 'hey' })
  },

  default: function () {
    // log the request and respond with 406
    res.status(406).send('Not Acceptable')
  }
})
image.png
  • res.location('/xxx')
app.get('/test', (req, res, next) => {
    // res.status(301)
    // res.location('/kong')
    res.redirect('/kong')  // 相当于上面两句话
    res.end()
    next()
})

app.get('/kong', (req, res, next) => {
    res.send('重定向地址')
    next()
})
image.png

单词学习

image.png

router.xxx

概况:共5个API
需要特别学习的API

  • 没有
  • 因为router就是一个阄割版的 app
app.use('/users', router)
const express = require('express')
const router = express.Router()

router.get('/', (req, res, next)=> {
    res.send('/user')
    next
})

router.get('/:id', (req, res, next)=> {
    res.send('/user/:id')
    next
})

router.get('/:id/edit', (req, res, next)=> {
    res.send('/user/:id/edit')
    next
})
image.png image.png

相关文章

网友评论

      本文标题:req.xxx API 讲解

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