preface
For a div engineer with a dream, the back end is also a dream direction. For those who are new to the back end, using frameworks will undoubtedly reduce the cost of learning. Both Express and KOA are well-known backend frameworks in the industry. Here we will take a look at Express.
The body of the
Express. XXX related API
express.json()
Normally, you can’t get the request body directly through request.body because the request data is transmitted as a stream. So when you get it, you also get it by stream
const express = require('express')
const app = express()
app.use('/', (request, response, next) => {
response.send('hi')
request.on('data', (chunk) => {
console.log(chunk.toString())
})
next()
})
Copy the code
This is a bit of a hassle, so you need to use express.json() to help convert to JSON objects
app.use(express.json())
app.use('/', (request, response, next) => {
response.send('hi')
console.log(request.body)
next()
})
Copy the code
express.static('yyy')
The API will first look for the corresponding file in the yyy directory, if not, then execute next to match the other conditional logic:
If (have file){sendFile(' XXX ')}else{next()}Copy the code
App related API
app.locals
Set. Unlike app.set, app.locals sets values that can be used in multiple middleware
app.set
/app.get
Use app.set(‘env’, ‘XXX ‘) to set env to XXX
Use app.get(‘env’) to get the set value
Typical use: app.set(‘case sensitive routing’, true). This parameter is set to false
Request the relevant API
request.get()
Used to get the request header
request.param('name')
Gets the routing and query string sections
request.range()
Limits whether multithreaded downloads are supported and the range of downloads
The response related API
response.send()
/response.sendFile()
Response content/response file
response.status()
Example Set the HTTP status code
response.location
Use response.redirect(‘/ XXX ‘) instead. Redirect (‘/ XXX ‘)
The router sample
//app.js const express = require('express') const app = express() const user = require('./routers/user') App.use ('/user', user) app.listen(3000, () => {console.log(' listening on port 3000 ')})Copy the code
// routers/user.js
const express = require('express')
const router = express.Router()
router.get('/', (req, res) => {
res.send('/user')
})
router.get('/:id', (req, res) => {
res.send('/user/:id')
})
router.get('/:id/edit', (req, res) => {
res.send('/user/:id/edit ')
})
module.exports = router
Copy the code