preparation

Import express

npm i express

Import the mongodb database tool

npm i mongoose

Used to parse information that the browser passes to the server because the Express server cannot recognize it directly

npm i body-parser

The project steps

Step 1: Create the index.js entry file

Step 2: Create a simple case in the entry file

// Import file
/ / into the express
const express = require('express')

// Create an app object
const app = express()
const port = 3000

// Send get requests to the server
app.get('/'.(req, res) = > {
  res.send('Hello World! ')})// Listen on the port
app.listen(port, () = > {
  console.log(`Example app listening at http://localhost:${port}`)})Copy the code

Start the server at this point

node index.js

Step 3: Set up the API interface

/ / check
app.get('/api/v1/read')
/ / to add
app.post('/api/v1/add')
/ / delete
app.delete('/api/v1/del')
/ / change
app.put('/api/v1/up')
Copy the code

Step 4: Create a controller (for processing data)

Create the Controller folder and create a main.js file

write

// Set the controller
const addList=(req,res) = >{
  res.send('add')// Set the interface to return add
}
const delList =(req,res) = >{
  res.send('del')// Set the interface to return del
}
const upList =(req,res) = >{
  res.send('up')// Set the interface to return up
}
const readList =(req,res) = >{
  res.send('read')// Set the interface to return read
}
// Export the controller
module.exports ={
  addList,delList,upList,readList
}
Copy the code

Step 5: Bind a controller to each interface

// Import the controller. Process.cwd () represents the server address
const mainController = require(process.cwd()+'/Controller/main')

// Bind to each interface

/ / check
app.get('/api/v1/read',mainController.readList)
/ / to add
app.post('/api/v1/add',mainController.addList)
/ / delete
app.delete('/api/v1/del',mainController.delList)
/ / change
app.put('/api/v1/up',mainController.upList)
Copy the code

Step 6: Test the interface

For example, test the READ interface

The interface address http://localhost:3000/api/v1/read

Request mode GET

Return message read

Test tool Postman