การใช้งานเกตเวย์ API
ออกแบบและตั้งค่าเกตเวย์ API ให้เป็นจุดเข้าสู่ระบบเพียงจุดเดียวสำหรับคำขอจากไคลเอ็นต์ไปยังไมโครเซอร์วิสของคุณ
การใช้งานเกตเวย์ API เป็นบทเรียน Node.js Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Node.js Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
API Gateway: The Front Door
In a microservices architecture, clients often need to interact with many different services. An API Gateway acts as a single, unified entry point for all client requests.
Think of it as the front desk of a large hotel. Instead of guests having to find specific rooms (microservices) themselves, they go to the front desk which directs them to the right place and handles common requests.

Why Use an API Gateway?
API Gateways solve several challenges that arise when using microservices:
- Simplifies Clients: Clients only need to know one endpoint (the gateway) instead of many microservice URLs.
- Request Routing: Directs incoming requests to the correct backend service.
- Common Concerns: Handles cross-cutting concerns like authentication, rate limiting, and logging at a single point.
- Service Aggregation: Can combine responses from multiple services into a single client-friendly response.
Gateway vs. Load Balancer
It's easy to confuse an API Gateway with a Load Balancer, but they serve different purposes:
- Load Balancer: Operates at the network layer (Layer 4) or application layer (Layer 7) to distribute traffic across multiple instances of the same service for high availability and performance.
- API Gateway: Operates at the application layer (Layer 7) and focuses on API-specific concerns. It routes requests to different services and can perform transformations or security checks.
They often work together, with a load balancer sitting in front of the API Gateway.
Key Responsibilities of a Gateway
An API Gateway takes on several crucial roles:
- Request Routing: Mapping specific API paths (e.g.,
/users) to the appropriate microservice. - Authentication & Authorization: Verifying user identity and permissions before forwarding requests.
- Rate Limiting: Controlling the number of requests a client can make within a certain timeframe.
- Caching: Storing frequently accessed data to reduce load on backend services and improve response times.
- Logging & Monitoring: Centralizing logs for all incoming requests and outgoing responses.
Building a Simple Gateway
You can build a custom API Gateway using Node.js and frameworks like Express.js. A popular library for proxying HTTP requests in Express is http-proxy-middleware.
This library makes it easy to forward requests from your gateway to your backend microservices, acting as a reverse proxy.
Basic Proxy Setup
Let's set up a simple Express.js server that acts as a proxy. This gateway will listen on port 3000 and forward all requests starting with /api to a mock 'users' microservice on port 3001.
Remember, for full functionality, you'd need an actual microservice running at http://localhost:3001.
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
const GATEWAY_PORT = 3000;
// Proxy all requests starting with /api to the users microservice
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:3001', // Target URL of your users microservice
changeOrigin: true, // Needed for virtual hosted sites
logLevel: 'debug' // Optional: for seeing proxy activity in console
})
);
// Simple root route for gateway status
app.get('/', (req, res) => {
res.send('API Gateway is running. Try /api/users (if microservice is active).');
});
app.listen(GATEWAY_PORT, () => {
console.log(`API Gateway listening on port ${GATEWAY_PORT}`);
console.log('Proxying /api to http://localhost:3001');
});Routing to Multiple Services
The power of an API Gateway comes from its ability to route requests to different microservices based on the request path, HTTP method, or other criteria.
You can define multiple proxy rules, each pointing to a different backend service. For example, /users goes to the user service, and /products goes to the product service.
Multi-Service Routing Example
Here, we extend our gateway to route requests for /users to a 'users-service' on port 3001 and requests for /products to a 'products-service' on port 3002.
The pathRewrite option is important: it removes the path prefix (e.g., /users) before forwarding the request to the target service.
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
const GATEWAY_PORT = 3000;
// Proxy for user-related requests
app.use(
'/users',
createProxyMiddleware({
target: 'http://localhost:3001', // Users Microservice URL
changeOrigin: true,
pathRewrite: { '^/users': '' }, // Remove /users prefix
logLevel: 'debug'
})
);
// Proxy for product-related requests
app.use(
'/products',
createProxyMiddleware({
target: 'http://localhost:3002', // Products Microservice URL
changeOrigin: true,
pathRewrite: { '^/products': '' }, // Remove /products prefix
logLevel: 'debug'
})
);
app.get('/', (req, res) => {
res.send('API Gateway is running. Try /users or /products (if microservices are active).');
});
app.listen(GATEWAY_PORT, () => {
console.log(`API Gateway listening on port ${GATEWAY_PORT}`);
console.log('Proxying /users to http://localhost:3001');
console.log('Proxying /products to http://localhost:3002');
});Centralized Middleware for Gateway
One of the biggest advantages of an API Gateway is applying middleware for common concerns before requests even reach your microservices.
You can implement Express middleware functions globally or for specific routes within your gateway to handle tasks like:
- Authentication: Verify JWTs or session tokens.
- Logging: Log every incoming request.
- Rate Limiting: Prevent abuse by limiting request frequency.
- Input Validation: Basic validation before forwarding.
Quick Check on Gateway
An API Gateway serves as a crucial component in a microservices setup. Let's test your understanding of its primary purpose.
Gateway Summary
You've learned about API Gateways, their importance in microservices, and how to implement a basic one using Express.js and http-proxy-middleware.
Key takeaways:
- API Gateways simplify client interactions by providing a single entry point.
- They handle routing, authentication, rate limiting, and other cross-cutting concerns.
- Express.js with
http-proxy-middlewareis a flexible way to build custom gateways.
Mastering API Gateways is essential for building robust and scalable microservices!
คำถามที่พบบ่อย
บทเรียน “การใช้งานเกตเวย์ API” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การใช้งานเกตเวย์ API” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Node.js Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การใช้งานเกตเวย์ API”
ออกแบบและตั้งค่าเกตเวย์ API ให้เป็นจุดเข้าสู่ระบบเพียงจุดเดียวสำหรับคำขอจากไคลเอ็นต์ไปยังไมโครเซอร์วิสของคุณ คุณปฏิบัติ Node.js Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Node.js Backend Development Bootcamp หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Node.js Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การใช้งานเกตเวย์ API” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Node.js Backend Development Bootcamp นี้ได้ไหม
ได้ บทเรียน Node.js Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- บทนำสู่สถาปัตยกรรมไมโครเซอร์วิส
- การพัฒนาไมโครเซอร์วิสด้วย Node.js
- การใช้งานเกตเวย์ API
- การสื่อสารระหว่างบริการด้วยคิวข้อความ