เส้นทางและการจัดการคำขอ
กำหนดเส้นทาง API จัดการเมธอด HTTP ต่าง ๆ และดึงข้อมูลจากเนื้อหาคำขอ พารามิเตอร์ และคำค้น
เส้นทางและการจัดการคำขอ เป็นบทเรียน NestJS Enterprise Backend APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน NestJS Enterprise Backend APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 3 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Understanding API Routes
When you build a web API, you need a way for clients (like a browser or mobile app) to send requests to specific functions on your server. This is where routes come in!
A route defines how a client's request URL (like /users or /products/1) maps to a particular action in your application code. It's like a street address for your API's functionalities.
HTTP Methods: The Action Verbs
Besides the URL, every request also uses an HTTP method, which tells the server what kind of action the client wants to perform. Common methods include:
- GET: Retrieve data (e.g., get a list of users).
- POST: Create new data (e.g., create a new user).
- PUT: Update existing data completely.
- PATCH: Partially update existing data.
- DELETE: Remove data.
NestJS uses decorators like @Get() or @Post() to link these methods to your controller functions.
Your First GET Route
Let's define a simple route to fetch some data. In NestJS, you use controllers to handle incoming requests and define routes.
The @Controller() decorator defines a base path for all routes within that controller. Then, methods like @Get() define specific endpoints and their HTTP methods.
Simple GET Route Example
Here's a basic NestJS app with a /greet endpoint. Run this example, then try accessing http://localhost:3000/greet in your browser or a tool like Postman.
You should see: Hello from NestJS!
// main.ts - Minimal NestJS app setup
import { NestFactory } from '@nestjs/core';
import { Module, Controller, Get } from '@nestjs/common';
@Controller('greet')
class GreetController {
@Get()
getGreeting(): string {
return 'Hello from NestJS!';
}
}
@Module({
controllers: [GreetController],
})
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
console.log('Server running on http://localhost:3000');
}
bootstrap();Dynamic Routes with Parameters
Often, you need routes that include dynamic data, like fetching a specific user by their ID (e.g., /users/123). These are called path parameters.
In NestJS, you define path parameters using a colon (:) followed by the parameter name in your @Get() decorator (e.g., @Get(':id')). You then extract its value using the @Param() decorator in your method signature.
Path Parameters Example
This example shows how to get a user ID from the URL path. If you run this, then visit http://localhost:3000/users/123, the output will be:
User ID: 123// main.ts - Minimal NestJS app setup
import { NestFactory } from '@nestjs/core';
import { Module, Controller, Get, Param } from '@nestjs/common';
@Controller('users')
class UsersController {
@Get(':id')
findUser(@Param('id') id: string): string {
return `User ID: ${id}`;
}
}
@Module({
controllers: [UsersController],
})
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
console.log('Server running on http://localhost:3000');
}
bootstrap();Filtering with Query Parameters
Query parameters are another way to pass data to your routes, often used for optional filtering, sorting, or pagination (e.g., /items?category=books&limit=5).
These parameters appear after a question mark (?) in the URL, as key-value pairs separated by ampersands (&). NestJS lets you easily access them using the @Query() decorator.
Query Parameters Example
This route uses query parameters to filter items. If you run this, then visit http://localhost:3000/items?category=books&limit=5, you'll see:
Category: books, Limit: 5// main.ts - Minimal NestJS app setup
import { NestFactory } from '@nestjs/core';
import { Module, Controller, Get, Query } from '@nestjs/common';
@Controller('items')
class ItemsController {
@Get()
findItems(
@Query('category') category: string,
@Query('limit') limit: string,
): string {
return `Category: ${category || 'all'}, Limit: ${limit || '10'}`;
}
}
@Module({
controllers: [ItemsController],
})
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
console.log('Server running on http://localhost:3000');
}
bootstrap();Handling Request Body (POST/PUT)
For operations that send a lot of data, like creating a new resource (POST) or updating an existing one (PUT), the data is typically sent in the request body.
The request body can contain structured data, often JSON. NestJS provides the @Body() decorator to easily parse and extract this data directly into your controller method's arguments.
Request Body Example (POST)
This example shows how to accept data in the request body for a POST request. If you send a POST request to http://localhost:3000/products with a JSON body like {"name": "Laptop", "price": 1200}, the output will be:
Product created: {"name":"Laptop","price":1200}// main.ts - Minimal NestJS app setup
import { NestFactory } from '@nestjs/core';
import { Module, Controller, Post, Body } from '@nestjs/common';
interface Product {
name: string;
price: number;
}
@Controller('products')
class ProductsController {
@Post()
createProduct(@Body() product: Product): string {
return `Product created: ${JSON.stringify(product)}`;
}
}
@Module({
controllers: [ProductsController],
})
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
console.log('Server running on http://localhost:3000');
}
bootstrap();Route Handling Check
Consider the following NestJS controller snippet:
import { Controller, Get, Param, Query } from '@nestjs/common';
@Controller('articles')
class ArticlesController {
@Get(':id')
getArticleById(@Param('id') id: string): string {
return `Article ID: ${id}`;
}
@Get()
searchArticles(@Query('keyword') keyword: string): string {
return `Searching for: ${keyword || 'all articles'}`;
}
}Which URL would successfully retrieve an article with ID "123"?
Recap: Routes & Requests
Great job! You've covered the fundamentals of defining API routes and handling different types of incoming data in NestJS:
- Routes map URLs to controller actions.
- HTTP methods (GET, POST, PUT, DELETE) define the action type.
- Path parameters (
@Param()) capture dynamic segments from the URL path. - Query parameters (
@Query()) extract optional key-value pairs from the URL string. - Request body (
@Body()) handles data sent with POST/PUT requests.
These are crucial building blocks for any robust RESTful API!
เรียนรู้ TypeScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 20
- บทเรียน
- 76
คำถามที่พบบ่อย
บทเรียน “เส้นทางและการจัดการคำขอ” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “เส้นทางและการจัดการคำขอ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส NestJS Enterprise Backend APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 3 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “เส้นทางและการจัดการคำขอ”
กำหนดเส้นทาง API จัดการเมธอด HTTP ต่าง ๆ และดึงข้อมูลจากเนื้อหาคำขอ พารามิเตอร์ และคำค้น คุณปฏิบัติ NestJS Enterprise Backend APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน NestJS Enterprise Backend APIs หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน NestJS Enterprise Backend APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 3 บทเรียน
บทเรียน “เส้นทางและการจัดการคำขอ” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน NestJS Enterprise Backend APIs นี้ได้ไหม
ได้ บทเรียน NestJS Enterprise Backend APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- เส้นทางและการจัดการคำขอ
- การดำเนินการ CRUD ด้วย TypeORM
- การจัดการข้อผิดพลาดและอินเตอร์เซปเตอร์