Node.js 和 Express 已成為建立可擴展 API 的重要工具,對於保持高效能和確保無縫用戶體驗至關重要。憑藉其事件驅動的架構,Node.js 可以有效地管理對即時應用程式不斷增長的需求,使其成為後端開發的首選。一項研究發現,68% 的開發人員表示使用 Node.js 提高了工作效率,這主要是由於它能夠在客戶端和伺服器端使用 JavaScript,從而簡化了開發過程。在本部落格中,我們將提供逐步指南,並附有精確的程式碼範例,以協助您使用 Node.js 和 Express 建立可擴展的 API。
非同步程式設計
Node.js 本質上是非同步的,允許它同時處理多個請求,而不會阻塞事件循環。此功能對於可擴展性至關重要,因為它可以實現高效的資源管理,特別是在高負載條件下。
模組化架構
採用模組化方法至關重要。透過將應用程式分解為更小的、獨立的模組,開發人員可以管理複雜性並促進獨立擴展。每個模組應該專注於特定的功能,這樣可以根據需要更輕鬆地測試、維護和擴展各個組件。
微服務
利用微服務架構可以顯著增強可擴展性。這種方法允許獨立擴展應用程式的不同部分,從而優化資源使用並提高整體效能。每個微服務都可以在不影響其他服務的情況下進行開發、部署和擴展。
有效的路由與中介軟體
Express.js 簡化了路由的建立和中間件的整合。中間件函數可以處理身份驗證、日誌記錄和錯誤處理等任務,使 API 更加健全且易於管理。正確組織路線和控制器對於保持程式碼庫的清晰度和效率至關重要。
錯誤處理與日誌記錄
實作全面的錯誤處理和記錄機制對於維護 API 穩定性至關重要。這確保了可以快速識別和解決問題,最大限度地減少停機時間並增強使用者體驗。
API 文件
建議使用 Swagger 等工具來撰寫 API 文件。記錄完善的 API 不僅可以幫助新開發人員更輕鬆地入職,還可以確保 API 對消費者來說是用戶友好的,從而實現更好的整合和使用。
效能最佳化
優化程式碼以提高效能至關重要。技術包括最小化同步操作、管理資源消耗以及利用快取策略(例如使用 Redis)來減少資料庫負載並縮短回應時間。
負載測試
定期負載測試對於識別潛在瓶頸並確保 API 能夠處理預期的流量峰值至關重要。監控反應時間和錯誤率等關鍵指標可以指導必要的調整和擴展策略。
我們建立了資料夾scalable-api。在程式碼編輯器中開啟此資料夾。
然後按照以下說明進行操作。
要初始化一個新的 Node.js 項目,請執行以下指令。
npm init -y
執行上述命令後,您的 package.json 檔案將會在該資料夾中建立。
現在,您必須執行以下命令來安裝express。
npm install express
執行上述指令後,將在根資料夾中建立node_modules資料夾和package-lock.json檔案。
現在您已經安裝了 Express,下一步是建立伺服器檔案並設定基本的 Express 伺服器。
您必須在根資料夾中建立一個名為 app.js 的檔案。
現在,您建立了檔案 app.js,並在 app.js 中設定了基本的 Express 伺服器。
const express = require('express'); const app = express(); const port = process.env.PORT || 3000; // Middleware to parse JSON bodies app.use(express.json()); // Basic route app.get('/', (req, res) => { res.send('Hello World!'); }); // Start the server app.listen(port, () => { console.log(`Server is running on port ${port}`); });
現在,完成後,透過在終端機中執行以下命令來運行伺服器。
node app.js
執行上述命令後,您將在終端機中看到以下訊息
Starting the server... Middleware set up. Route set up. Server is running on port 3000
要存取伺服器,請開啟 Chrome 瀏覽器或您正在使用的任何瀏覽器,導航至 http://localhost:3000 ,您將看到「Hello World」訊息。
如上圖。
使用 Node.js 和 Express 建立可擴充 API 的後續步驟通常包括:
Adding More Routes:
You have to define additional routes to handle different endpoints. For example, let’s add routes for /api and /users.
// ... existing code ... // New route for /api app.get('/api', (req, res) => { res.send('API endpoint'); }); // New route for /users app.get('/users', (req, res) => { res.send('Users endpoint'); }); // ... existing code ...
You to add above code in your app.js file and update your app.js file.
Now, let’s test the new routes.
start your server by running:
node app.js
Now, open your browser, and go to http://localhost:3000/api , you’ll see the message “API endpoint”
Now, you should navigate to **http://localhost:3000/users,** you’ll see the message “Users endpoint”, shown in below screen
Now, your next step will be to connect to a database. For this, we’ll use we'll use MongoDB with Mongoose, a popular ODM (Object Data Modeling) library for MongoDB and Node.js.
You’ve to run the following command to install the Mongoose.
npm install mongoose
Let’s see how you can update your app.js file to connect to MongoDB database.
const mongoose = require('mongoose'); // Connect to MongoDB mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Connected to MongoDB')) .catch(err => console.error('Could not connect to MongoDB', err)); // ... existing code ...
Connect to MongoDB: Use mongoose.connect to connect to your MongoDB database. Replace 'mongodb://localhost:27017/mydatabase' with your actual MongoDB connection string if it's different.
Now, that for that, You must first have set up your MongoDB, If you haven’t, let’s set it up now. Use MongoDB Atlas (Cloud Database). You have to create a MongoDB Atlas account, Go to MongoDB Atlas and sign up for free account.
once you sign up via or Google or GitHub Account, You’ll see below screen after login.
You’ll to click on visit MongoDB Atlas, Click on Create a New Cluster,
Once you click on Create as shown in above screen, you’ll be redirect to below screen, select M0 free version.
you have to keep your configuration as it is by default, now click on Create Deployment.
once, you click on that, you’ll come to this screen.
You’ve to notedown, your username and password, once you click on “Create Database User”,
Once you click on “Choose a connection method”,
now, choose, Choose “Connect to your application”, You’ll see below screen.
Now, you’ll see connection string like this - mongodb+srv://
replace it with your username and password you noted down earlier.
Now that, you to copy your MongoDB string and have to replace in your app.js code, and you have to update it.
now, you to run your node app.js file again in your terminal. You’ll see the message “Connected to MongoDB”
So, now you see above successful message, now, next step is to add simple logging middleware using Morgan which is a popular HTTP request logger middleware for Node.js.
To install Morgan, run below command.
npm install morgan
now, you’ve to update, your app.js file to use Morgan.
const express = require('express'); const morgan = require('morgan'); // Import morgan const app = express(); const port = process.env.PORT || 3000; console.log('Starting the server...'); const mongoose = require('mongoose'); // Replace with your actual MongoDB connection string const mongoURI = 'mongodb+srv://: @cluster0.mongodb.net/myFirstDatabase?retryWrites=true&w=majority'; mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Connected to MongoDB')) .catch(err => console.error('Could not connect to MongoDB', err)); // Middleware to parse JSON bodies app.use(express.json()); // Use morgan for logging app.use(morgan('tiny')); console.log('Middleware set up.'); // Basic route app.get('/', (req, res) => { console.log('Received a request on /'); res.send('Hello World!'); }); // New route for /api app.get('/api', (req, res) => { res.send('API endpoint'); }); // New route for /users app.get('/users', (req, res) => { res.send('Users endpoint'); }); console.log('Route set up.'); // Start the server app.listen(port, () => { console.log(`Server is running on port ${port}`); });
now, run your node app.js, go to http://localhost:3000/ and you’ll see log entry for request in terminal. This step will add basic logging to your application.
Your next step is to define a schema and model for your MongoDB collections using Mongoose. This will allow you to interact with your database in a structured way.
You have to create a new file named user.js in a models directory you may need to create the models directory if it doesn't exist). You’ve define a User Schema and model for user.
const mongoose = require('mongoose'); // Define the User schema const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true } }); // Create the User model const User = mongoose.model('User', userSchema); module.exports = User;
Now, you’ve to update the app.js to Use the User Model:
In app.js,import the User modelandcreate a route to add a new user:
const express = require('express'); const morgan = require('morgan'); const mongoose = require('mongoose'); const User = require('./models/user'); // Import the User model const app = express(); const port = process.env.PORT || 3000; console.log('Starting the server...'); // Replace with your actual MongoDB connection string const mongoURI = 'mongodb+srv://: @cluster0.mongodb.net/myFirstDatabase?retryWrites=true&w=majority'; mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Connected to MongoDB')) .catch(err => console.error('Could not connect to MongoDB', err)); // Middleware to parse JSON bodies app.use(express.json()); // Use morgan for logging app.use(morgan('tiny')); console.log('Middleware set up.'); // Basic route app.get('/', (req, res) => { console.log('Received a request on /'); res.send('Hello World!'); }); // New route for /api app.get('/api', (req, res) => { res.send('API endpoint'); }); // New route for /users app.get('/users', (req, res) => { res.send('Users endpoint'); }); // Route to add a new user app.post('/users', async (req, res) => { try { const user = new User(req.body); await user.save(); res.status(201).send(user); } catch (error) { res.status(400).send(error); } }); console.log('Route set up.'); // Start the server app.listen(port, () => { console.log(`Server is running on port ${port}`); });
now, that you’ve to open postman, you can also use desktop postman agent, click on new request, select request type to“Post”, Enter the URL - http://localhost:3000/users , now, selectbody tab, selectrow and jsonthere.
enter the following json in text area.
{ "name": "John Doe", "email": "john.doe@example.com", "password": "password123" }
and once you send the request, it will reflect in yourMongoDB Atlas account, you have to go database and have to select cluster0, findyour databasewhich you’ve create,go to the user, and here you’ll found the information, you send via a request. just like below screen.
As we successfully added users to your MongoDB database, the next step is toimplement additional CRUD (Create, Read, Update, Delete) operationsfor your User model. This will allow you to manage users more effectively.
Let's start by adding routes for reading, updating, and deleting users.
1. Read (GET) Users
Add a route to get all users and a route toget a user by ID.
// ... existing code ... // Route to get all users app.get('/users', async (req, res) => { try { const users = await User.find(); res.send(users); } catch (error) { res.status(500).send(error); } }); // Route to get a user by ID app.get('/users/:id', async (req, res) => { try { const user = await User.findById(req.params.id); if (!user) { return res.status(404).send('User not found'); } res.send(user); } catch (error) { res.status(500).send(error); } }); // ... existing code ...
2. Update (PUT) Users
Add a route toupdate a user by ID.
// ... existing code ... // Route to update a user by ID app.put('/users/:id', async (req, res) => { try { const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true }); if (!user) { return res.status(404).send('User not found'); } res.send(user); } catch (error) { res.status(400).send(error); } }); // ... existing code ...
3. Delete (DELETE) Users
Add a route todelete a user by ID.
// ... existing code ... // Route to delete a user by ID app.delete('/users/:id', async (req, res) => { try { const user = await User.findByIdAndDelete(req.params.id); if (!user) { return res.status(404).send('User not found'); } res.send(user); } catch (error) { res.status(500).send(error); } }); // ... existing code ...
once, you update your above code in your app.js file,
start your server using node app.js command,
now, send request to get all users: You’ll see below screen, in your http://localhost:3000/users
when you runget user by id, you’ll see in terminal as well on local host as well.
when you update any information, you’ll able to see it here. we changed name from john doe to Ethan lee,
when you run adelete request, one user will be deleted.
so, we successfully implemented and tested all thebasic CRUD Operations for your API.
Centralized error handling helps manage errors gracefully and provides consistent error responses.
Add Error Handling Middleware
// ... existing code ... // Error handling middleware app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send({ error: 'Something went wrong!' }); }); // Start the server app.listen(port, () => { console.log(`Server is running on port ${port}`); });
Using environment variables helps manage configuration settings securely.
npm install dotenv
2.Create a .env File:
PORT=3000 MONGODB_URI=mongodb+srv://: @cluster0.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
this is your updated app.js
require('dotenv').config(); const express = require('express'); const morgan = require('morgan'); const mongoose = require('mongoose'); const cors = require('cors'); const User = require('./models/user'); const app = express(); const port = process.env.PORT || 3000; console.log('Starting the server...'); mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Connected to MongoDB')) .catch(err => console.error('Could not connect to MongoDB', err)); // Middleware to parse JSON bodies app.use(express.json()); // Use morgan for logging app.use(morgan('tiny')); // Use cors for handling CORS issues app.use(cors()); console.log('Middleware set up.'); // Basic route app.get('/', (req, res) => { console.log('Received a request on /'); res.send('Hello World!'); }); // CRUD routes // ... existing CRUD routes ... // Error handling middleware app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send({ error: 'Something went wrong!' }); }); console.log('Route set up.'); // Start the server app.listen(port, () => { console.log(`Server is running on port ${port}`); });
For a more secure API, you might want to add basic authentication. Here’s a simple example using HTTP Basic Auth:
Install Basic Auth Middleware:
npm install express-basic-auth
2.Update app.js to Use Basic Auth:
const basicAuth = require('express-basic-auth'); // ... existing code ... // Use basic auth for all routes app.use(basicAuth({ users: { 'admin': 'supersecret' }, challenge: true })); // ... existing code ...
Using tools like Swagger can help you document your API endpoints.
Install Swagger UI
npm install swagger-ui-express swagger-jsdoc
Create a Swagger Configuration File
create a swagger.js file in root folder, you’ve to add following code to your file.
const swaggerJsDoc = require('swagger-jsdoc'); const swaggerUi = require('swagger-ui-express'); const swaggerOptions = { swaggerDefinition: { openapi: '3.0.0', info: { title: 'User API', version: '1.0.0', description: 'A simple Express User API' }, servers: [ { url: 'http://localhost:3000' } ] }, apis: ['./app.js'] // Path to the API docs }; const swaggerDocs = swaggerJsDoc(swaggerOptions); module.exports = (app) => { app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs)); };
Update app.js to Use Swagger
Add the following code to your app.js file to set up Swagger:
update your app.js file
require('dotenv').config(); const express = require('express'); const morgan = require('morgan'); const mongoose = require('mongoose'); const cors = require('cors'); const User = require('./models/user'); const setupSwagger = require('./swagger'); // Import the Swagger setup function const app = express(); const port = process.env.PORT || 3000; console.log('Starting the server...'); mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Connected to MongoDB')) .catch(err => console.error('Could not connect to MongoDB', err)); // Middleware to parse JSON bodies app.use(express.json()); // Use morgan for logging app.use(morgan('tiny')); // Use cors for handling CORS issues app.use(cors()); console.log('Middleware set up.'); // Basic route app.get('/', (req, res) => { console.log('Received a request on /'); res.send('Hello World!'); }); // CRUD routes // ... existing CRUD routes ... // Setup Swagger setupSwagger(app); // Error handling middleware app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send({ error: 'Something went wrong!' }); }); console.log('Route set up.'); // Start the server app.listen(port, () => { console.log(`Server is running on port ${port}`); });
Add Swagger Comments to Your Routes
Add comments to your routes in app.js to document them with Swagger. Here’s an example for the GET /users route:
/** * @swagger * /users: * get: * summary: Retrieve a list of users * responses: * 200: * description: A list of users * content: * application/json: * schema: * type: array * items: * type: object */ app.get('/users', async (req, res) => { try { const users = await User.find(); res.send(users); } catch (error) { res.status(500).send(error); } }); /** * @swagger * /users/{id}: * get: * summary: Retrieve a single user by ID * parameters: * - in: path * name: id * required: true * schema: * type: string * description: The user ID * responses: * 200: * description: A single user * content: * application/json: * schema: * type: object * 404: * description: User not found */ app.get('/users/:id', async (req, res) => { try { const user = await User.findById(req.params.id); if (!user) { return res.status(404).send('User not found'); } res.send(user); } catch (error) { res.status(500).send(error); } }); // Add similar comments for other routes...
now, when you go to http://localhost:3000/api-docs , use your username and password which is in app.js
You’ll get this, you should be able to access the Swagger UI and see the documentation for your API.
You have successfully built a scalable API with Node.js and Express, complete with CRUD operations, basic authentication, and API documentation using Swagger. This should provide a comprehensive demo for your technical article. You can deploy your API over cloud which make it accessible for all people on the internet, you can use services like Heroku for deployment.
Building scalable APIs with Node.js and Express requires a strategic approach, including modular architecture, optimized performance with non-blocking I/O, clustering, efficient database management, and robust security measures. By implementing caching, monitoring tools, and auto-scaling, your API can handle thousands of requests per second, ensuring reliability and performance under heavy loads. Ready to scale your API with Node.js and Express? Contact us today to build a future-proof API solution for your business needs!
Node.js offers several advantages for API development, including its asynchronous, non-blocking architecture that allows for handling multiple requests simultaneously. This leads to improved performance and scalability. Additionally, Node.js uses JavaScript, enabling developers to work across both the client and server sides, which streamlines the development process.
Express.js is a minimal and flexible web application framework that simplifies the process of building APIs with Node.js. It provides robust routing, middleware support, and easy integration with various databases, making it an excellent choice for developing RESTful APIs quickly and efficiently.
To ensure your API is scalable, consider implementing a microservices architecture, which allows different components to be scaled independently. Additionally, optimize your code for performance, use caching strategies, and conduct regular load testing to identify and address potential bottlenecks.
Best practices for error handling in Node.js APIs include using middleware to catch errors globally, logging errors for monitoring and debugging, and providing meaningful error messages to clients. It's also essential to handle different types of errors (e.g., validation errors, database errors) appropriately to enhance user experience.
ViitorCloud は、Node.js と Express を使用したスケーラブルな API の構築に特化した、ビジネス ニーズに合わせた包括的な開発サービスを提供します。当社の経験豊富な開発者チームは、API 設計とアーキテクチャのベスト プラクティスを利用して、アプリケーションが高負荷を効率的に処理できるようにします。パフォーマンスの最適化と堅牢な開発プロセスに重点を置いた ViitorCloud は、現在の需要を満たすだけでなく将来の成長にも適応する API の作成を支援し、デジタル ソリューションの強力な基盤を提供します。
以上是使用 Node.js 和 Express 建立可擴展的 API的詳細內容。更多資訊請關注PHP中文網其他相關文章!