-
Introduce http module
let http = require('http');
-
Create service instance
let server = http.createServer();
-
Waiting for request
server.on('request',(request,response) => { console.log('请求收到'); let str = ''; if (request.url == '/') { str = 'welcome to Home'; } else { str = `welcome to ${ request.url}`; } response.write(str);// 发送数据 response.end();// 结束连接 // 等价于 response.end(str);// 发送响应并结束响应(更常用) })
-
When the client requests, it will automatically trigger the server's request request event, and then call the callback function
-
The request processing function (callback function) has two parameters
- request
- The request object can be used to obtain some request information from the client
- response
- The response object can be used to send response information to the client
- There is a method: write can be used to send response data to the client
- write can be used multiple times, but end must be used in the end, otherwise the client will wait forever
- request
-
Bind the port number, start the server
server.listen(3000,() => { console.log('服务绑定成功'); })
-
-
Run: Enter the current node js file in cmd or webStorm or software with terminal to run the service. Then enter the address in the browser window. In this example, port 3000 is set. You can visit http://localhost:3000/ to access the simple http service created by nodejs.
-
End the service: close the current window or ctrl+c
Nodejs creates a simple http service
Guess you like
Origin blog.csdn.net/chen__cheng/article/details/114331316
Recommended
Ranking