Create interface steps (summarize previous lessons)
Create the basic server: app.js
1
2
3
4
5
6const express = require('express')
const app = express()
//main code
app.listen(80, function(){
console.log('Express server running at http://127.0.0.1')
})
Create an API routing module
apiRouter.js routing module
1
2
3
4const express = require('express')
const apiRouter = express.Router()
//main code
module.exports = apiRouterapp.js import and register routing module
1
2const apiRouter = require('./apiRouter.js')
app.use('/api', apiRouter)
Write a GET interface
1
2
3
4
5
6
7
8apiRouter.get('/get', (req, res) => {
const query = req.query //req.query can access the parameters sent to the server in the form of query strings, see 4.1.8 for details.
res.send({
status: 0, //0 succeeds, 1 fails
msg:'GET request succeed',
data:query
})
})
Write POST interface
1
2
3
4
5
6
7
8apiRouter.post('/post', (req, res) => { //Get the URL-encoded data sent by the client to the server through the request body
const body = req.body //req.body object, which can access the request body data, see 4.5.5 for details.
res.send({
status: 0, //0 succeeds, 1 fails
msg:'POST request succeed',
data:body
})
})Note: If you want to get the request body data in URL-encoded format, you must configure the middleware:
1
app.use(express.urlencoded({extended:false}))
Interface cross domain problem
The above GET/POST interface does not support cross-domain requests. (It appears that postman can request success, but the request in the html page cannot be successful.)