zoukankan      html  css  js  c++  java
  • Nodejs核心模块之net和http的使用详解

    前言

    net和http模块都是node核心模块之一,他们都可以搭建自己的服务端和客户端,以响应请求和发送请求。

    net模块服务端/客户端

    这里写的net模块是基于tcp协议的服务端和客户端,用到net.createServer和net.connect实现的一个简单请求与响应的demo。

    //tcp服务端
    var net = require('net')
    var sever=net.createServer(function(connection){
      //客户端关闭连接执行的事件
     connection.on('end',function(){
      //  console.log('客户端关闭连接')
     })
     connection.on('data',function(data){
      console.log('服务端:收到客户端发送数据为'+data.toString())
    })
    //给客户端响应的数据
     connection.write('response hello')
    })
    sever.listen(8080,function(){
      // console.log('监听端口')
    })
    //tcp客户端
    var net = require('net')
    var client = net.connect({port:8080},function(){
      // console.log("连接到服务器")
    })
    //客户端收到服务端执行的事件
    client.on('data',function(data){
      console.log('客户端:收到服务端响应数据为'+data.toString())
      client.end()
    })
    //给服务端传递的数据
    client.write('hello')
    client.on('end',function(){
      // console.log('断开与服务器的连接')
    })

    运行结果

      

    http模块四种请求类型

    http服务端:

    http.createServer创建了一个http.Server实例,将一个函数作为HTTP请求处理函数。这个函数接受两个参数,分别是请求对象(req)处理请求的一些信息和响应对象(res)处理响应的数据。

    //http服务端
    const http = require("http");
    var fs = require("fs");
    var url = require('url')
     
    http.createServer(function (req, res) {
      var urlPath = url.parse(req.url);
      var meth = req.method
      //urlPath.pathname 获取及设置URL的路径(path)部分
      //meth 获取请求数据的方法,一个路径只能被一种方法请求,其他方法请求时返回404
      if (urlPath.pathname === '/' && meth === 'GET') {
        res.write(' get ok');
      } else if (urlPath.pathname === '/users' && meth === 'POST') {
        res.writeHead(200, {
          'content-type': 'text/html;charset=utf-8'
        });
        fs.readFile('user.json', function (err, data) {
          if (err) {
            return console.error(err);
          }
          var data = data.toString();
          // 返回数据
          res.write(data);
        });
      } else if (urlPath.pathname === '/list' && meth === 'PUT') {
        res.write('put ok');
      } else if (urlPath.pathname === '/detail' && meth === 'DELETE') {
        res.write(' delete ok');
      } else {
        res.writeHead(404, {
          'content-type': 'text/html;charset=utf-8'
        });
        res.write('404')
      }
      res.on('data', function (data) {
        console.log(data.toString())
      })
     
    }).listen(3000, function () {
      console.log("server start 3000");
    });

    http客户端:

    http模块提供了两个创建HTTP客户端的方法http.request和http.get,以向HTTP服务器发起请求。http.get是http.request快捷方法,该方法仅支持GET方式的请求。

    http.request(options,callback)方法发起http请求,option是请求的的参数,callback是请求的回掉函数,在请求被响应后执行,它传递一个参数,为http.ClientResponse的实例,处理返回的数据。

    options常用的参数如下:

    1)host:请求网站的域名或IP地址。
    2)port:请求网站的端口,默认80。
    3)method:请求方法,默认是GET。
    4)path:请求的相对于根的路径,默认是“/”。请求参数应该包含在其中。
    5)headers:请求头的内容。

    nodejs实现的爬虫其实就可以用http模块创建的客户端向我们要抓取数据的地址发起请求,并拿到响应的数据进行解析。

    get

    //http客户端
    const http = require("http");
    // 发送请求的配置
    let config = {
      host: "localhost",
      port: 3000,
      path:'/',
      method: "GET",
      headers: {
        a: 1
      }
    };
    // 创建客户端
    let client = http.request(config, function(res) {
      // 接收服务端返回的数据
      let repData='';
      res.on("data", function(data) {
        repData=data.toString()
        console.log(repData)
      });
      res.on("end", function() {
        // console.log(Buffer.concat(arr).toString());
      });
    });
    // 发送请求
    client.end();结束请求,否则服务器将不会收到信息

    客户端发起http请求,请求方法为get,服务端收到get请求,匹配路径是首页,响应数据:get ok。

    post

    //http客户端
    var http = require('http');
    var querystring = require("querystring");
    var contents = querystring.stringify({
      name: "艾利斯提",
      email: "m778941332@163.com",
      address: " chengdu",
    });
    var options = {
      host: "localhost",
      port: 3000,
      path:"/users",
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Content-Length": contents.length
      }
    };
    var req = http.request(options, function (res) {
      res.setEncoding("utf8");
      res.on("data", function (data) {
        console.log(data);
      })
    })
     
    req.write(contents);
    //结束请求,否则服务器将不会收到信息
    req.end(); 
    //响应的数据为
    {
      "user1" : {
        "name" : "mahesh",
        "password" : "password1",
        "profession" : "teacher",
        "id": 1
      },
      "user2" : {
        "name" : "suresh",
        "password" : "password2",
        "profession" : "librarian",
        "id": 2
      }
     }

    客户端发起http请求,请求方法为post,post传递数据,匹配路径是/users,服务器响应请求并返回数据user.json里的内容。

    put

    //http客户端
    const http = require("http");
    // 发送请求的配置
    let config = {
      host: "localhost",
      port: 3000,
      path:"/list",
      method: "put",
      headers: {
        a: 1
      }
    };
    // 创建客户端
    let client = http.request(config, function(res) {
      // 接收服务端返回的数据
      let repData='';
      res.on("data", function(data) {
        repData=data.toString()
        console.log(repData)
      });
      res.on("end", function() {
        // console.log(Buffer.concat(arr).toString());
      });
    });
    // 发送请求
    client.end();

    客户端发起http请求,请求方法为put,服务端收到put请求,匹配路径为/list,响应数据:put ok

     delect

    //http delete请求客户端
    var http = require('http');
    var querystring = require("querystring");
    var contents = querystring.stringify({
      name: "艾利斯提",
      email: "m778941332@163.com",
      address: " chengdu",
    });
    var options = {
      host: "localhost",
      port: 3000,
      path:'/detail',
      method: "DELETE",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Content-Length": contents.length
      }
    };
    var req = http.request(options, function (res) {
      res.setEncoding("utf8");
      res.on("data", function (data) {
        console.log(data);
      })
    })
     
    req.write(contents);
    req.end();

    服务端收到delete请求,匹配路径为/detail,响应数据:delete ok

    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    转自:

    https://www.jb51.net/article/158913.htm

  • 相关阅读:
    js获取页面所有搜索条件
    js计算两经纬度之间的距离
    .NET MVC 序列化与反序列化
    微信浏览器内禁止页面回退返回
    Winform组合ComboBox和TreeView实现ComboTreeView
    如何在Oracle触发器中使用查询语句
    DevExpress Winform:纯代码方式创建PopupMenu
    DevExpress GridView 鼠标热点追踪 高亮显示行
    Task.Wait and “Inlining”
    重置Visual Studio 2017的配置
  • 原文地址:https://www.cnblogs.com/xiaohuizhenyoucai/p/11016725.html
Copyright © 2011-2022 走看看