mirror of
https://github.com/expressjs/expressjs.com.git
synced 2026-02-27 03:08:34 +00:00
* Add description to each page (#1639) * fix: rersolved description issues and also added the descriptions in the es folder * feat: added descriptions in all the languages
3.5 KiB
Executable File
3.5 KiB
Executable File
layout, title, menu, lang, description
| layout | title | menu | lang | description |
|---|---|---|---|---|
| page | Express basic routing | starter | th | Learn the fundamentals of routing in Express.js applications, including how to define routes, handle HTTP methods, and create route handlers for your web server. |
เส้นทางเบื้องต้น
เส้นทาง (Routing) เป็นการกำหนดการอ้างอิงว่าแอปพลิเคชันจะตอบสนองต่อคำร้องขอของเครื่องลูกข่ายที่มายังปลายทาง (endpoint) โดยเฉพาะได้อย่างไร ซึ่งเป็น URI (หรือ path) และวิธีการร้องขอ HTTP (GET, POST, และ อื่นๆ)
แต่ละเส้นทางสามารถมีได้มากกว่าหนึ่งฟังชันส์จัดการ (handler function) ซึ่งสามารถดำเนินการเมื่อเส้นทางถูกจับคู่
การกำหนดเส้นทางใช้โครงสร้างดังนี้:
app.METHOD(PATH, HANDLER)
เมื่อ:
appเป็นอินสแตนซ์ของexpress.METHODเป็น HTTP request method, เป็นตัวพิมพ์เล็ก.PATHเป็นเส้นทางบนเซิร์ฟเวอร์.HANDLERเป็นฟังชันส์ที่กระทำเมื่อเส้นทางถูกจับคู่.
การสอนนี้จะสมมติว่าอินสแตนซ์ของ `express` ชื่อว่า `app` จะถูกสร้างขึ้นเมื่อรันเซิร์ฟเวอร์ ถ้าไม่คุ้นเคยกับการสร้าง app และโครงสร้างของมัน ดูเพิ่มเติมได้ที่ [ตัวอย่าง Hello world](/{{ page.lang }}/starter/hello-world.html)
ตัวอย่างดังต่อไปนี้จะแสดงให้เห็นการกำหนดเส้นทางอย่างง่าย
ตอบสนองด้วยข้อความ Hello World! บนเพจหลัก:
app.get('/', (req, res) => {
res.send('Hello World!')
})
ตอบสนองต่อการร้องขอด้วยวิธี POST บนเส้นทาง root (/) บนเพจหลักของแอปพลิเคชัน:
app.post('/', (req, res) => {
res.send('Got a POST request')
})
ตอบสนองต่อการร้องขอด้วยวิธี PUT บนเส้นทาง /user:
app.put('/user', (req, res) => {
res.send('Got a PUT request at /user')
})
ตอบสนองต่อการร้องขอด้วยวิธี DELETE บนเส้นทาง /user:
app.delete('/user', (req, res) => {
res.send('Got a DELETE request at /user')
})
สำหรับข้อมูลเพิ่มเติมเกี่ยวกับการกำหนดเส้นทาง ดูได้ที่ [คำแนะนำการกำหนดเส้นทาง](/{{ page.lang }}/guide/routing.html)