美文网首页
NodeJS-http模块

NodeJS-http模块

作者: 走停2015_iOS开发 | 来源:发表于2018-06-30 17:47 被阅读7次

搭建一个http的服务器,用户处理用户发送的http请求,需要使用node提供的一个模块:http;

//    1 加载http模块
var http  = require('http');
//    2.通过http模块下的CreatServer创建并且返回一个web服务器对象
var server = http.createServer(function(){
    console.log('有客户端请求来了');
console.log(req);
});
server.on('error',function(err){

   console.log(err);
});
server.on('listening',function(){
    console.log('listening-----');
});
server.on('request',function(req,res){
    console.log('有客户端请求来了');
   console.log(req);
  console.log('有客户端请求来了');
    //console.log(req);
    //console.log(res);
    //把数据写入头信息当中,可以调用多次
    res.setHeader('miaov','leo');
    //写入头信息(状态码,描述文字,头信息),只能在当前调用中使用一次,并且在end介绍前
    res.writeHead(200,'miaov',{
    //告诉客户端我现在发送你的是什么类型的数据
      'content-type':'text/html,charset=utf-8', //Hello
      // 'content-type':'text/plain',//<h1>Hello</h1>
    });
    //发送一个数据块到响应正文中
    //res.write("hello");
    res.write('<h1>Hello</h1>');
    //当所有正文和头信息发送完成以后调用该方法告诉服务器数据已经全部
    //发送完成了,这个方法在每次发送完消息之后,必须调用,并且在最后调用
    //如果在该方法中传入参数,会自动调用`write`方法,再调用`end`方法
    res.end('<h1>Hello</h1>');
});
//3.端口号0-1024都被系统应用测试用完了
server.listen(8081,'localhost');
//console.log(server.address());

-------------------------打印--------------------------------------
/usr/local/bin/node server1.js
listening-----
有客户端请求来了
有客户端请求来了

3B594F9A-A67E-4200-BF7B-3CAED3DF519A.png

res.writeHead(200,'miaov',{
//告诉客户端我现在发送你的是什么类型的数据
'content-type':'text/html,charset=utf-8', //Hello
// 'content-type':'text/plain',//<h1>Hello</h1>
});

9C650380-C253-4689-ABDA-53FF83CDCFBC.png

res.setHeader('miaov','leo');

B50F6BFB-CEFC-4DC2-B2B8-C450A097E9A0.png

相关文章

  • NodeJS-http模块

    搭建一个http的服务器,用户处理用户发送的http请求,需要使用node提供的一个模块:http; res.wr...

  • nodejs-http模块

    1.http服务器http.createServer([options][, requestListener]) ...

  • nodejs-http内置模块

    安装http协议 npm i http -S 启动web服务器 运行 只有80端口才不写,其它都要加端口号http...

  • Nodejs-HTTP模块抓包分析

    例1: TCP的数据部分是http报文,例1是没有分包的,http请求和响应报文都是以TCP为载体的。例2: (1...

  • nodejs-http笔记

    创建于2016 应该是当时看到别人的文章之后的笔记,如果作者看到请联系我 http事务解剖 创建服务 还可以有另一...

  • 第五天笔记 nodejs-http

    使用 HTTP 服务器或客户端功能必须调用require('http')。 Node 里的 HTTP 接口支持协议...

  • python常用模块!!

    os模块: stat模块: sys模块: hashlib,md5模块: random模块: types模块: at...

  • 2018-08-19

    Angular 2 技能图谱 模块 自定义模块 根模块 特性模块 共享模块 核心模块 内置模块 Applicati...

  • 【时间管理100讲】精髓全在这里啦

    理论模块 精力管理。 行动管理。 学习模块。 高空模块。 反思模块。 运动模块。 阅读模块。 旅行模块。 人际关系...

  • python基础学习(三)

    常用模块 String模块 数学模块 随机模块 OS模块 os.path模块 re模块 常用函数及操作 列表操作 ...

网友评论

      本文标题:NodeJS-http模块

      本文链接:https://www.haomeiwen.com/subject/vwtxuftx.html