Start with the bear example on the official website

First open the example to see the directory structure

  • In the bear.js file is to create our bear module

  • Node_models/is the dependency we need created via NPM install. // Press CTRL + Alt +O to bring up the console console

  • Once you have downloaded the dependencies, you can view them through package.json

    Zaipackage. json, we can see that there are three dependencies. What are they used for?

    First, Express is a framework for back-end NodeJS

    Mongoose is a linked database. An ORM(metadata that describes the mapping between objects and databases, and automatically persists the objects in the program to a relational database) Body-Parser can extract POST content from front-end HTTP requests

  • In the server.js file, you can configure the APP, routing, and API interfaces

Define the bear module and provide it with a name field

Nodejs content starts in server.js, so let’s open server.js and start writing the back end


Set port


Generally speaking, we use port 8080. When the port is occupied, we can also use port 8081, 8082, etc. (There will be a collation and correction of common port occupied events later)

mongoose.connect('mongodb://localhost/27017'); // connect to our database
Copy the code

Remember the bear module we defined in bear.js? Now we can quote!


The router. Use (function())Copy the code

It is important to use middleware to verify the information in the request to ensure that the data is safe and reliable. When an error is reported, we can also throw error. Express4.0 has been optimized to ensure that paths are executed in the order listed. The information is returned as JSON data, which is an API standard. Test middleware by printing “Something is happing”.

Next ()Copy the code

The meaning of this statement is so that this route does not stop while other routes are executing.

Create the BEAR using the POST request

  • Create an instance from the bear module
  • Assign the information (name) of bear from the request to bear.name
  • Save the bear, detect and send the error
  • Return message “Massage: ‘Bear Created'”

Now that we’ve created a post route for our app, we can still use it

The router. The route ()Copy the code

To handle multiple routes to the same URL, we can handle all requests ending in /bear

With the Postman detection

Get the specific bear by: bear_id

The code is as follows:

Covers all routes required by the API