express及常用API

核心就是中間件

概念

  • express 是TJ大神用Node.js封裝的一個(gè)Web框架
  • 核心概念是中間件

編程模型

  • 使用app.use(fn)
  • 編程模型

主要的api類型

express(內(nèi)置的中間件)

內(nèi)置的中間件,返回的是一個(gè)函數(shù)。比如express.json()

常用的

const app = express()
app.use('/xxx',fn)
app.get('/xxx',fn)
app.post('/xxx',fn)
app.router('/xxx').all(fn1).get(fn2)

next

next()
next(error)

  • 自定義errorHandler
  • app.use((err,req,res,next) => {})
  • next('route')

api

express

  • 內(nèi)置的中間件
  • express.json //用于處理請(qǐng)求體為JSON的請(qǐng)求
app.use(express.json())

app.use('/xxx',(req,res,next) => {
    console.log(req.body) //打印出來的是個(gè)JSON
})
//如果不寫的話
app.use('/xxx',(req,res,next) => {
    console.log(req.body) //打印出來的是個(gè)undefined
    req.on('data',(chunk) => {
        chunk.toString()    
    })
})

  • express.static()
//獲取當(dāng)前目錄下的public路徑。注意:請(qǐng)求的時(shí)候就不需要帶上/public這樣的前綴了
app.use(express.static(path.join(__dirname, 'public')));
  • express.Router()


  • 其他的
    • express.row()//處理文件,二進(jìn)制流
    • express.text()
    • express.urlencoded()

app

應(yīng)用設(shè)置(模板配置、中間件、掛載路由)

  • app.locals //設(shè)置變量
app.locals.title = '標(biāo)題啦'
  • set/get 優(yōu)先推薦使用app.locals
app.set('case sensitive routing',true)//大小寫敏感
app.set('views', path.join(__dirname, 'views'));//渲染的位置
app.set('view engine','ejs') //注意是view,而不是views
app.get('env')
  • app.get/post/put/delete
  • app.render
app.render(view, [locals], callback)
  • app.use
  • app的api


request

  • req.get('請(qǐng)求頭屬性')
app.get('/get', (req, res, next) => {
    console.log(req.get('User-Agent'));
    next();
});
  • req.params
//axios.get('/get/1/nick')
app.get('/get/:id/:name', (req, res, next) => {
    console.log(req.params); // {id:1 ,name: 'nick'}
    next();
});
  • req.query
//axios.get('/get?age=18')
app.get('/get', (req, res, next) => {
    console.log(req.query);// {age: 18}
    res.send('hello ,this is get method');
    next();
});
  • req.range()//分片,服務(wù)器是否支持范圍請(qǐng)求
  • request.png


response

res.range //用來分片

res.append與res.set res.append

  • res.append 是往里加,加同樣的頭都會(huì)保留
  • res.set 是往里面設(shè)置,設(shè)置同樣的只能保留一個(gè)

res.set

  • 分區(qū)

res.render()/res.download()

// send the rendered view to the client
res.render('index')

// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render('index', function (err, html) {
  res.send(html)
})

// pass a local variable to the view
res.render('user', { name: 'Tobi' }, function (err, html) {
  // ...
})

res.download('/report-12345.pdf')

res.download('/report-12345.pdf', 'report.pdf')

res.download('/report-12345.pdf', 'report.pdf', function (err) {
  if (err) {
    // Handle error, but keep in mind the response may be partially-sent
    // so check res.headersSent
  } else {
    // decrement a download credit, etc.
  }
})

res.send()/ res.sendFile()

res.headersSent()

app.get('/', function (req, res) {
  console.dir(res.headersSent) // false
  res.send('OK')
  console.dir(res.headersSent) // true
})

res.status()

res.status(403).end()
res.status(400).send('Bad Request')
res.status(404).sendFile('/absolute/path/to/404.png')

res.set()/res.get()

res.set('Content-Type', 'text/plain')

res.set({
  'Content-Type': 'text/plain',
  'Content-Length': '123',
  ETag: '12345'
})

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')
  }
})

res.send跟res.write 不能同時(shí)使用

  • write是流式的操作
  • send是一次性的
  • response.png

express.Router

  • 就是一個(gè)閹割版的express
  • router.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容