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!

HTML and React can be seamlessly integrated through JSX to build an efficient user interface. 1) Embed HTML elements using JSX, 2) Optimize rendering performance using virtual DOM, 3) Manage and render HTML structures through componentization. This integration method is not only intuitive, but also improves application performance.

React efficiently renders data through state and props, and handles user events through the synthesis event system. 1) Use useState to manage state, such as the counter example. 2) Event processing is implemented by adding functions in JSX, such as button clicks. 3) The key attribute is required to render the list, such as the TodoList component. 4) For form processing, useState and e.preventDefault(), such as Form components.

React interacts with the server through HTTP requests to obtain, send, update and delete data. 1) User operation triggers events, 2) Initiate HTTP requests, 3) Process server responses, 4) Update component status and re-render.

React is a JavaScript library for building user interfaces that improves efficiency through component development and virtual DOM. 1. Components and JSX: Use JSX syntax to define components to enhance code intuitiveness and quality. 2. Virtual DOM and Rendering: Optimize rendering performance through virtual DOM and diff algorithms. 3. State management and Hooks: Hooks such as useState and useEffect simplify state management and side effects handling. 4. Example of usage: From basic forms to advanced global state management, use the ContextAPI. 5. Common errors and debugging: Avoid improper state management and component update problems, and use ReactDevTools to debug. 6. Performance optimization and optimality

Reactisafrontendlibrary,focusedonbuildinguserinterfaces.ItmanagesUIstateandupdatesefficientlyusingavirtualDOM,andinteractswithbackendservicesviaAPIsfordatahandling,butdoesnotprocessorstoredataitself.

React can be embedded in HTML to enhance or completely rewrite traditional HTML pages. 1) The basic steps to using React include adding a root div in HTML and rendering the React component via ReactDOM.render(). 2) More advanced applications include using useState to manage state and implement complex UI interactions such as counters and to-do lists. 3) Optimization and best practices include code segmentation, lazy loading and using React.memo and useMemo to improve performance. Through these methods, developers can leverage the power of React to build dynamic and responsive user interfaces.

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.


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

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.