Deploy nodejs rest api
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:
- A text editor (VS Code is recommended)
- Node. js (download and install from the official website)
- 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

Vue 2's reactivity system struggles with direct array index setting, length modification, and object property addition/deletion. Developers can use Vue's mutation methods and Vue.set() to ensure reactivity.

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

TypeScript enhances React development by providing type safety, improving code quality, and offering better IDE support, thus reducing errors and improving maintainability.

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

The article explains using useReducer for complex state management in React, detailing its benefits over useState and how to integrate it with useEffect for side effects.

Functional components in Vue.js are stateless, lightweight, and lack lifecycle hooks, ideal for rendering pure data and optimizing performance. They differ from stateful components by not having state or reactivity, using render functions directly, a

The article discusses strategies and tools for ensuring React components are accessible, focusing on semantic HTML, ARIA attributes, keyboard navigation, and color contrast. It recommends using tools like eslint-plugin-jsx-a11y and axe-core for testi
