创建一个简单的 HTTP 服务器
使用 Node.js 构建一个基本的 HTTP 服务器,以了解它如何处理网页请求和响应。
No configuration found for ID: b48817530b566f278c48f52373106d73bf291a8341297371299def7f3c718169
-
GET request:
1curl -X GET http://localhost:3000Expected output:
1Received a GET request -
POST request:
1curl -X POST http://localhost:3000Expected output:
1Received a POST request
No configuration found for ID: 6657ae142ea0813d72bdbd61418d68f3a1fb32ea43cd342d75bc9365940a8906
Show Solution
The code for index.js is given below:
Solution: Responding based on the request method
1const http = require('http'); 2 3const server = http.createServer((req, res) => { 4 if (req.method === 'GET') { 5 res.write('Received a GET request'); 6 } else if (req.method === 'POST') { 7 res.write('Received a POST request'); 8 } 9 res.end(); 10}); 11 12server.listen(3000, () => { 13 console.log('Server is running on http://localhost:3000'); 14});
-
Line 4: Checks if
req.methodis GET; if so, sends "Received a GET request". -
Line 6: Checks if
req.methodis POST; if so, sends "Received a POST request". -
Line 9: Calls
res.end()to complete the response.
-
Line 4: Checks if
req.methodis GET; if so, sends “Received a GET request”. -
Line 6: Checks if
req.methodis POST; if so, sends “Received a POST request”. -
Line 9: Calls
res.end()to complete the response.