• Node.js http服务器搭建和发送http的get、post请求


    1.Node.js 搭建http服务器

    1.1创建server.js

    var http = require('http');
    var querystring = require('querystring');
    http.createServer(function (request, response) {
        console.log('receive request');
        response.writeHead(200, { 'Content-Type': 'text-plain' });
        response.end('Hello World
    ');
    }).listen(8124);
    console.log("node server start ok  port "+8124);

    1.2执行 server.js

    node server.js

    1.3服务器启动

      通过浏览器地址请求:http://localhost:8124

    2.发送GET请求

    2.1发送get请求通过聚合服务器获取微信新闻数据

    var http = require('http');
    
    var querystring = require('querystring');
    
    http.get('http://v.juhe.cn/weixin/query?key=f16af393a63364b729fd81ed9fdd4b7d&pno=1&ps=10', function (response) {
        var body = [];
        console.log(response.statusCode);
        console.log(response.headers);
        console.log(response);
        response.on('data', function (chunk) {
            body.push(chunk);
        });
    
        response.on('end', function () {
            body = Buffer.concat(body);
            console.log(body.toString());
        });
    });

    2.2 执行 get_demo.js

    node get_demo.js

    2.3获取的结果打印

    3.发送POST请求

    3.1发送post请求通过聚合服务器获取微信闻数据

    var http = require('http');
    
    var querystring = require('querystring');
    
    var postData = querystring.stringify({
      'key' : 'f16af393a63364b729fd81ed9fdd4b7d',
      'pno':'1',
      'ps':10
    });
    
    var options = {
      hostname: 'v.juhe.cn',
      path: '/weixin/query',
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(postData)
      }
    };
    
    var req = http.request(options, (res) => {
      console.log(`STATUS: ${res.statusCode}`);
      console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
      res.setEncoding('utf8');
      res.on('data', (chunk) => {
        console.log(`BODY: ${chunk}`);
      });
      res.on('end', () => {
        console.log('No more data in response.')
      })
    });
    
    req.on('error', (e) => {
      console.log(`problem with request: ${e.message}`);
    });
    
    // write data to request body
    req.write(postData);
    req.end();

    3.2 执行 post_demo.js

    node post_demo.js

    3.3获取的结果打印

    文章来源:https://blog.csdn.net/u010046908/article/details/52742357

  • 相关阅读:
    centos yum安装与配置vsFTPd FTP服务器(转)
    CentOS 6.9安装配置nmon
    Linux 中将用户添加到组的指令
    linux 设置用户组共享文件
    linux时间同步ntpdate
    java获取端口号,不用request
    centos6.5 yum安装redis
    Centos6 yum安装nginx
    Nginx 不支持WebSocket TCP
    django中的分页应用 django-pure-pagination
  • 原文地址:https://www.cnblogs.com/flyingeagle/p/9219222.html
Copyright © 2020-2023  润新知