• 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

  • 相关阅读:
    Java NIO系列教程(十二) Java NIO与IO
    Java NIO系列教程(十一) Pipe
    Java NIO系列教程(十) Java NIO DatagramChannel
    Java NIO系列教程(九) ServerSocketChannel
    C#使用cmd运行命令并返回控制台输出信息
    分割nginx日志
    redis启动警告解决
    git worktree 目录修复
    git worktree 稀疏检出(sparseCheckout)
    python json dumps datetime类型报错
  • 原文地址:https://www.cnblogs.com/flyingeagle/p/9219222.html
Copyright © 2020-2023  润新知