Nodejs create server steps

1. Introduce the http module. This module is a built-in module

 const http = require('http')

2. There is a createServer() function on http to create a server.

 const server = http.createServer() //得到个服务器对象

3. Listen to the event: listen to the request event sent by the user

 server.on( 'request',function(req,res){ /* req:request简写。语法上只是一个形参而已,请求消息 res:response简写,响应消息 */ console.log('一个用户发起了请求') //此时这里没有响应。按照协议:一个请求必须对应一个响应啊。 res.end('hello node .js') //这就是响应。 } )

4. Open a port

 server.listen(3000)

When the port is opened, it is called: the server is opened and the server is mounted successfully.

Then we access this server

http://localhost:3000

http:127.0.0.1:3000

The above two functions are the same: the representative is accessing the server on your own computer.

own IP

https://ift.tt/h0uzjEc

The post nodejs create server steps first appeared on Lenix Blog .

This article is reprinted from https://blog.p2hp.com/archives/9123
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment