Home >Web Front-end >Front-end Q&A >Deploy nodejs rest api

Deploy nodejs rest api

WBOY
WBOYOriginal
2023-05-11 14:28:06635browse

In today's Internet era, building efficient and fast back-end services is essential. NodeJS excels in this area, making it fast and easy to build efficient web services. REST API is also a very popular method of building web services in today's Internet industry. It can greatly reduce the amount of code, simplify port handling, and has many benefits. In this article, we will learn how to quickly deploy REST API using NodeJS and ExpressJS.

Environment preparation

Before we start, we need to set up an environment:

  1. A text editor (VS Code is recommended)
  2. Node. js (download and install from the official website)
  3. Postman (test tool, can be downloaded and installed from the official website)

Initialize the project

First, we open the terminal and create a New project directory:

mkdir project-name
cd project-name

Then, we use npm init to create a new package:

npm init

npm init You will be asked to enter Some basic information, such as author name, project name, version, etc. Some default settings can be used directly, just modify some of your own information.

Next, we will need to install the following dependencies:

npm install express body-parser cors —save
  • Express is the framework we use to build REST APIs.
  • body-parser is a middleware for parsing POST requests and JSON data.
  • Cors is a plugin that allows web applications to enable CORS (Cross-Origin Resource Sharing) on ​​another domain

Create a Service

Now, let’s do Create a new file called app.js, this will be the starting point for our NodeJS REST API service. We can build this service with the help of the Express framework:

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express()

const port = 3000

app.use(cors())

app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())

app.listen(port, () => {
  console.log(`Server running on port ${port}`)
})

In the above code snippet, we import Express, body-parser and cors. We also used the app.listen() method that listens on port 3000. Finally, we enable the cors and body-parser middleware through the app.use() method.

Creating Routes

The next step will be to create routes, which are required to implement our REST API service. Routing can be understood as a set of rules for how the service should respond after a request enters the service.

We can create a routes folder in the project root directory, create the index.js file in it, and add the following content:

const express = require('express')
const router = express.Router()

router.get('/posts', (req, res) => {
  res.status(200).send('All posts')
})

module.exports = router;

In the above code, we create a new route and create a GET request for /posts on the route. The request will return a status code of 200 and the text "All posts".

Next, we will enable the route. We go back to the app.js file and add the following:

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express()

const postRoutes = require('./routes/index');
const port = 3000

app.use(cors())

app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())

app.use('/api', postRoutes);

app.listen(port, () => {
  console.log(`Server running on port ${port}`)
})

In the above code, we import the route defined in routes/index.js and Use the app.use('/api', postRoutes) method to apply routes to our REST API service. Then, when calling a GET request at localhost:3000/api/posts, it should return "All posts".

Database Connection

Of course, in a real project, the data we need to request and obtain will be stored in the database, so we need to discuss here how to use NodeJS to connect to the database .

We will use MongoDB as our database and mongoose to connect to it. We can install mongoose by running the following command in the command line:

npm install mongoose --save

Next, let’s create a models folder and add a new file in it post. js to describe a simple data model.

const mongoose = require('mongoose');

const postSchema = new mongoose.Schema({
  title: { type: String, required: true },
  content: { type: String, required: true },
  author: { type: String, required: true },
}, { timestamps: true });

module.exports = mongoose.model('Post', postSchema);

In the above code, we defined a model called Post to define our data and used the timestamps option when creating it.

Now, we are going to use Mongoose to connect to the local MongoDB database. You can add the following content in the app.js file:

const mongoose = require('mongoose');
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')

const postRoutes = require('./routes/index');
const PORT = process.env.PORT || 3000;

const app = express();

app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

mongoose.connect('mongodb://localhost/posts', { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', function() {
    console.log('Successfully connected to MongoDB!');
})

app.use('/api', postRoutes);

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

The database URL of the above code is set to mongodb://localhost/posts, which means that the database name is posts and is located in our local MongoDB instance. We also used the default port (27017) for the Mongoose port. Note that the deprecated code in Mongoose has been fixed, so we have to use the useUnifiedTopology option.

Implement routing

We have set up routing in the server and can successfully connect to our database. Next, we'll configure more routes to handle POST requests and get data from our database.

First, we add a new POST request to our route and extract the title, content, author, and other necessary information from the request body. and store the data into the database. Here, we will create a MongoDB document assuming a database named "posts" and passing the Post model itself.

const express = require('express');
const router = express.Router();
const Post = require('../models/post.js');

router.get('/posts', (req, res) => {
  Post.find()
  .then(data => res.json(data))
  .catch(err => res.status(400).json(`Error: ${err}`));
});

router.get('/posts/:id', (req, res) => {
  Post.findById(req.params.id)
  .then(data => res.json(data))
  .catch(err => res.status(400).json(`Error: ${err}`));
});

router.post('/posts', (req, res) => {
  const newPost = new Post(req.body);
  newPost.save()
  .then(() => res.json('Post added!'))
  .catch(err => res.status(400).json(`Error: ${err}`));
});

module.exports = router;

In the code at the top, we first import our model file and create all the required routes for GET or POST requests. The GET request uses Post.find() to extract all database entries from the MongoDB database, while our POST request uses newPost.save() to store new data into the database table.

Use Postman for testing

After completing the above steps, you can use Postman to test our REST API.

First, we try to retrieve data using a GET request. We can retrieve all posts by accessing http://localhost:3000/posts.

Next, we try to create new data using a POST request. We can do this by visiting http://localhost:3000/posts and adding a new JSON data body in the body of the request. to create a new article.

Finally, we can also retrieve a single entry using a GET request. We can retrieve a single post provided by the ID by accessing http://localhost:3000/posts/:id.

With these simple steps, we can implement a simple REST API and connect to the MongoDB database. Of course, there are many other operations that can continue to improve this API, such as operations such as updating and deleting entries, but we recommend that you try to write these functions yourself to gain a deeper understanding of the process.

The above is the detailed content of Deploy nodejs rest api. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn