req.xxx API 讲解

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
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容