10-创建基本的http服务程序

var http=require('http')  加载http模块
var server=http.createServer()  创建http服务对象

//监听用户请求事件(request事件)
// request对象 包含了用户请求报文中的所有内容,
//             通过request对象可以获取用户提交过来的数据
// response对象 用来响应用户的一些数据
//              当服务器要向客户端响应数据的时候必须使用response对象
// 简写为 req res

server.on('request',function (req,res) {
   //这里如果不写代码 则浏览器会一直加载转圈 因为服务器未响应请求

   res.write('hello ')

   //这里必须要结束响应 不然还是会一直加载
    //因为没有告诉客户端什么时候响应完毕
   res.end()

})

//启动服务
server.listen(8080,function () {
    console.log('服务器启动了 请访问: http://localhost:8080')
})

注解:

 地址栏输入:http://localhost:8080即可访问到
 注意:输入不存在的地址 例如:http://localhost:8080/123/456
         结果也能输出 hello 因为server.on('request',function (req,res))
             里面只监听了用户请求 只要有请求就响应hello
              并没有判断不同请求作出不同响应
 端口号随便写 也可以写9090 地址栏输入:http://localhost:9090即可访问到

简写:

var http=require('http')
http.createServer( function (req,res) {
    //req.url拿到用户请求的路径

    res.setHeader('Content-Type','text/plain;charset=utf-8')
    res.write('hello 你好')

    res.end()

}).listen(8080,function () {
    console.log('服务器启动了 请访问: http://localhost:8080')
}) 

猜你喜欢

转载自blog.csdn.net/MDZZ___/article/details/91376204