步骤:
1、加载http核心模块
2、使用http.createServer()方法创建一个Web服务器(返回一个Server实例)
3、注册request请求事件。当客户请求过来,就会自动触发服务器的request请求事件,然后执行第二个参数:回调处理函数。
4、绑定端口号,启动服务器
1 var http=require(‘http‘) 2 var server=http.createServer() 3 server.on(request,function(request,response){ 4 console.log("收到客户端请求,请求路径是:"+request.url) 5 response.write("hello") 6 response.write(" node.js") 7 response.end() 8 }) 9 server.listen(3000,function(){ 10 console.log("服务器启动成功了,可以通过http://127.0.0.1:3000/ 来进行访问"); 11 })
服务器:提供对数据的服务(发请求、接收请求、处理请求、发送响应)
request 请求对象:用来获取客户端的一些请求信息
response 响应对象:用来给客户端发送响应信息
response.write 可以使用多次,但最后 一定要用end来结束响应,否则客户端会一直等待
原文:https://www.cnblogs.com/technicist/p/12688490.html