If, like me, you’ve always been on the front end, never had a chance to take the first step back, and are more or less at a loss for the back end, this article will be a good fit. You can implement a complete set of add, delete, change and review REST apis and solve cross-domain problems in just 10 minutes. This can be very rewarding and is a good time to lift the veil on back-end Node.js. The technical stack is Express + MongoDB. 12.0.0+ is recommended for node. js version. The MongoDB server is easy to download and install by yourself.

Initialize the project

Create a new folder, open the terminal, type yarn init, package.json and it will be created automatically.

Install the libraries you need to use

yarn add mongoose express nodemon cors
Copy the code
  • Mongoose: Database
  • Express: server-side framework
  • Nodemon: automatically monitors and refreshes node services
  • Cors: A library for solving cross-domain problems

Create a server file

Don’t be put off by the words “server files.” It’s easy to start with a general operation: add a command to the scripts object of package.json

"scripts": {    
    "dev": "nodemon server.js"  
},
Copy the code

Then create server.js in the root directory to import the libraries to use

Const cors = require('cors') app.use(cors()) // Json parsing app. Use (express. Json ()) / / configure a get request path for testing / / http://localhost:5002/list app. Get ('/list, (the req, Json ({data: true})}) // Set the listening port of the service app.listen(5002)Copy the code

Terminal type yarn dev, a back-end services have run in this way, can the browser to access http://localhost:5002/list to view, will have the following return, then I will feel I again! Full stack boss is just around the corner.

Connecting to a Database

Next we need to refine server.js, connect the database, and create a model.

Create a folder in the root directory named models, create a file /models/user.js, and edit user.js

Const mongoose = require('mongoose') const mongoose = require('mongoose') Const userSchema = new Mongoose.Schema({title: {type: String, required: true}, createdAt:{type: Date, default: ()=> Date.now() } }) module.exports = mongoose.model('user', userSchem)Copy the code

Return /server.js and add the database connection code under app.use(express.json())

Const mongoose = require('mongoose') const userModel = require('./models/user') Mongoose. Connect ('mongodb://localhost/test', {// A database named test is automatically created useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true })Copy the code

Implement a real interface

Implement the first real interface: add a piece of data. We want to achieve through the interface to a set of data to add http://localhost:5002/add, the goal is to successfully fall into to the database, or in the server. The js, connect the database code below:

app.post('/add', async(req, res)=>{
    const data = {title: req.body.title}
    let user = new userModel(data)
    try {
        await user.save()
        res.json({data: true})
    } catch(err){
        res.status(500).json({message: err.message})
    }
})
Copy the code

Find a client, send a POST request, use body to pass the parameter, I used postman, test results as shown in the picture below, it means we succeeded!

Then rewrite before implementation/list interface, http://localhost:5002/list to write the data query.

app.get('/list', async (req, res) => {    try {
        const data = await userModel.find().sort({createdAt: 'desc'})
        res.json(data)
    } catch(err){
        res.status(500).json({message: err.message})
    }})
Copy the code

Let’s see what the test looks like. It’s successful.

Modify the implementation of the interface

Modify the interface code as follows, simple and easy to read, here uses the PUT request, according to the ID of the data to be modified.

http://localhost:5002/edit, for example, feed the body mass and query JSON objects, request type to PUT

app.put('/edit', async (req, res) => { if (! req.body._id) { res.status(500).json({ data: }) return} let user= await usermodel.findByid (req.body._id) user.title = req.body.title try {user= await user.save() res.status(200).json({ data: 'ok' }) } catch (error) { res.status(500).json({ message: error.message }) } })Copy the code

Postman try request effect, success!

Delete the implementation of the interface

DELETE interface in this hash format, pass an ID to DELETE the corresponding data, the request type is DELETE

Example: http://localhost:5002/remove/60d8311b7a8d4a36b01f987f

app.delete('/remove/:id', async (req, res) => { if (! req? .params? .id) { res.status(500).json({ data: 'not found' try {return}}) await userModel. FindByIdAndDelete (the req. Params. Id) res. Status (200). The json ({data: 'ok' }) } catch (error) { res.status(500).json({ message: error.message }) } })Copy the code

Test the

The end of the

Above is all content, code to the lot on https://github.com/jiazehua/nodejs-express-REST-API-helloworld, including the POSTMAN test files are also derived in the root directory.