美文网首页
Node - http

Node - http

作者: 酷热summer | 来源:发表于2020-04-11 22:32 被阅读0次

    一、创建http 服务

    Node.js 可以创立简单的 http 服务,引入 http 模块即可。
    新建 index.js

    const http = require("http");
    const server = http.createServer();
    server.on("request", (req, res)=> {
      res.end("Hello World");
    });
    server.listen(9999);
    

    其中第二至第五行可合并为:

    const server = http.createServer((req,res)=>{
      res.end("Hello World");
    });
    

    然后在终端启动此文件: node path/index.js,在浏览器中输入 localhost:9999即可看到返回的 "Hello World"

    二、req / res

    主要介绍下可通过 reqres 可获得/设置哪些内容:

    • req.url 可获得除协议、域名外的其他路径、query 参数,不可获得锚点。 eg:http://localhost:9999/fdsjkf/fklfks?jfkdjl=12&jkfd=kfo#jdfd 会返回 /fdsjkf/fklfks?jfkdjl=12&jkfd=kfo#jdfd
    • req.method: 请求的方法
    • req.headers:请求头信息
    • res.setHeader(key,value):设置响应头
    • res.statusCode:设置响应的状态码

    三、数据接收与处理

    server.request((req,res)=>{}) 方法中,我们可以对发起的请求方法、请求头进行判断,对请求中发送的数据进行数据监听,使用 req.on('data',function(){})来处理接收的数据,使用req.on('end',function(){})在数据发送完成式时做一些操作。由于发送的数据量可能比较大,所以会持续执行 on('data')的回调函数,代码示例如下:

    const server = http.createServer((req, res) => {
      const contentType = req.headers['content-type'];
      res.writeHead(200, { 'Content-Type': 'text/plain;charset=utf-8' }); // 解决汉字乱码
      res.write(`请求的路径为:${req.url}`);
      res.write(`请求的方法为:${req.method}`);
      switch (contentType) {
        case 'text/plain':
          let str = '';
          req.on('data', function (data) {
            str += data.toString('utf-8');
          });
          req.on('end', function () {
            res.end(`你发送的数据为:${str}`);
          });
          break;
        default:
          res.end('content-type 无匹配项');
          break;
      }
    });
    

    四、数据 解析

    Content-Type 中,常用的有:

    • text/plain: 纯文本
    • application/json: json 格式
    • x-www-form-urlencoded:表单数据

    通常,text/plain 在服务端接收后不需要做特殊处理。application/json 使用 JSON.parse() / JSON.stringify() 可以进行必要的格式转换,x-www-form-urlencoded 可以使用 nodejs 自带模块 querystring 进行解析,表单提交的数据格式为: a=1&b=2&c=3,服务端解析方式如下:

        case 'application/x-www-form-urlencoded': {
          let str = '';
          req.on('data', function (data) {
            str += data.toString('utf-8');
          });
          req.on('end', function () {
            console.log(qs.parse(str));
            res.end(`你发送的数据为:${str}`);
          });
          break;
        }
    

    五、url 解析

    node 提供了 url 模块,方便进行 url 解析,使用方式如下:

    const url = require('url');
    const server = http.createServer((req, res) => {
      const reqUrl = url.parse(req.url, true);
      console.log(reqUrl);
    });
    

    此时,请求的 urlhttp://localhost:9999/a/b/c&c=1&d=2&e=3#abc,则服务端会打印出:

    Url {
     protocol: null,
     slashes: null,
     auth: null,
     host: null,
     port: null,
     hostname: null,
     hash: null,
     search: null,
     query: [Object: null prototype] {},
     pathname: '/a/b/c&c=1&d=2&e=3',
     path: '/a/b/c&c=1&d=2&e=3',
     href: '/a/b/c&c=1&d=2&e=3' 
    }
    

    六、http 发送请求

    http 模块可以通过 createServer() 建立一个服务器,也可以通过 http.request() 向其他服务器发送请求,示例如下:

    const http = require('http');
    const server = http.createServer();
    
    server.on('request', (req, res) => {
      const { url, headers, method } = req;
      const options = {
        hostname: 'www.xxx.com',
        port: 80,
        path: url,
        method,
        headers
      };
      options.headers.host = 'www.xxx.com';
      let str = '';
      const request = http.request(options, (requestRes) => {   // 发送请求
        requestRes.on('data', data => {
          str += data;
        });
        requestRes.on('end', err => {
          console.log(err);
          console.log(str);
          res.end(str);
        });
      });
      request.end();
    });
    
    server.listen(8989);
    

    createServer() 中接收数据类似,request 也有 on('data')on('end') 来接收服务端返回的数据,在完全接收完后,将接收到的数据通过 res.end() 返回给客户端。

    相关文章

      网友评论

          本文标题:Node - http

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