node-http创建服务端和客户端

http模块是nodeJS的核心模块。它可以创建客户端(发起请求)和服务端(监听请求)。

1. 客户端client

应用: 

1. 爬虫

2. 中间层-解决跨域问题

let http = require('http');

// 服务端发送的请求不存在跨域问题
let client = http.request({
  hostname: 'localhost',
  port: 3000,
  path: '/aaa?name=lyra',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
}, function(response) {// response可读流
  response.on('data', function(data) {
    console.log(JSON.parse(data.toString()));
  })
});
// client相当于可写流
client.end("a=1&b=2");// 发送请求体

2. 服务端server

let http = require('http');
let querystring = require('querystring');
let url = require('url');

let server = http.createServer(function(request, response) {// 监听函数;请求到来时触发
  /////////// request-->可读流
  /****1. 请求行***/
 console.log(request.method.toLowerCase());// 大写
 console.log(request.url); // 端口号后面的部分;不包含hash; eg: /aaa?a=b
  const {pathname, query} = url.parse(request.url, true); // true表示解析成对象
  // pathname: /aaa   query: {a: 'b'}
 console.log(request.httpVersion);
  /****2. 请求头***/
 //console.log(request.headers); // 所有属性名小写
  /****3. 请求体***/
  // 请求体通过监听data获取;on监听的回调是异步执行
  let arr = [];
  request.on('data', function(data) {// 只有请求体有内容,才会触发
    arr.push(data);
  });
  request.on('end', function(err) { // 不论请求体是否有内容,总会触发
    let content = Buffer.concat(arr).toString(); // username=lyra
    // 可写流的参数只能是字符串和buffer
    if (request.headers['content-type'] === 'application/x-www-form-urlencoded') {
      let result = JSON.stringify(querystring.parse(content));// =parse(content, '&', '=')
      /////////// response-->可写流(字符串或者Buffer)
      /******1. 响应行 */
      response.statusCode = 200; // 必须是有效状态码
      /******2. 响应头 */
      response.setHeader('Content-Type', 'application/json');
      /******3. 响应体 */
      // end前面还可以使用write方法
      response.end(result); //立即触发;应该放置在end回调中
    }
  })
});
// 监听特定的端口和IP
/**
 * 端口号最大65535;一般使用3000+的端口,因为很多会被占用
 */
server.listen(3000, 'localhost', () => {
  console.log('3000 started');
})

3. nodemon 

node monitor。实时监控node服务的内容变化,自动重启服务。

命令:

nodemon 具体文件

4. curl

从命令行发起http请求

// 通过命令行发起http请求
// GET 
curl -v http://localhost:3000  //-v查看信息
// POST
curl -v -X POST -d "username=lyra"//localhost:3000 //-X 指定请求方式  -d 指定传递数据
// 带请求头
curl -v --header "Range:bytes=0-3"  http://www.baidu.com
原文地址:https://www.cnblogs.com/lyraLee/p/12183095.html