1

nodejs创建服务器步骤

 1 year ago
source link: https://blog.p2hp.com/archives/9123
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

nodejs创建服务器步骤 | Lenix Blog

1、引入http模块。这个模块是内置模块

const http = require('http')

2、http身上有个createServer() 函数 创建服务器的。

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

3、 兼听事件: 兼听用户发的请求事件

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

4、开放一个端口

 server.listen(3000)

当端口开启后,叫:服务器开启了、服务器挂载成功了。

然后我们访问这个服务器

http://localhost:3000

http:127.0.0.1:3000

上面的两个作用一样:代表访问的是你自己电脑上的服务器。

自己的IP
http://192.168.30.128:3000

设置响应头信息    res.writeHead(200,{'Content-Type':"text/html;charset=utf8"})


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK