美文网首页JavaScript 进阶营
07、GET/POST请求 工具模块- Web 模块

07、GET/POST请求 工具模块- Web 模块

作者: 夜幕小草 | 来源:发表于2017-07-25 23:24 被阅读120次

在很多场景中,我们的服务器都需要跟用户的浏览器打交道,如表单提交。
表单提交到服务器一般都使用 GET/POST 请求。
本章节我们将为大家介绍 Node.js GET/POS T请求。
01、获取GET请求内容
由于GET请求直接被嵌入在路径中,URL是完整的请求路径,包括了?后面的部分,因此你可以手动解析后面的内容作为GET请求的参数。
node.js 中 url 模块中的 parse 函数提供了这个功能。

var http = require('http');
var url = require('url');
var util = require('util');
 
http.createServer(function(req, res){
    res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
    res.end(util.inspect(url.parse(req.url, true)));
}).listen(3000);

02、获取 URL 的参数
我们可以使用 url.parse 方法来解析 URL 中的参数,代码如下:

var http = require('http');
var url = require('url');
var util = require('util');
 
http.createServer(function(req, res){
    res.writeHead(200, {'Content-Type': 'text/plain'});
 
    // 解析 url 参数
    var params = url.parse(req.url, true).query;
    res.write("网站名:" + params.name);
    res.write("\n");
    res.write("网站 URL:" + params.url);
    res.end();
 
}).listen(3000);

03、获取 POST 请求内容
POST 请求的内容全部的都在请求体中,http.ServerRequest 并没有一个属性内容为请求体,原因是等待请求体传输可能是一件耗时的工作。
比如上传文件,而很多时候我们可能并不需要理会请求体的内容,恶意的POST请求会大大消耗服务器的资源,所有node.js 默认是不会解析请求体的,当你需要的时候,需要手动来做。

var http = require('http');
var querystring = require('querystring');
 
http.createServer(function(req, res){
    // 定义了一个post变量,用于暂存请求体的信息
    var post = '';     
 
    // 通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中
    req.on('data', function(chunk){    
        post += chunk;
    });
 
    // 在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。
    req.on('end', function(){    
        post = querystring.parse(post);
        res.end(util.inspect(post));
    });
}).listen(3000);

结果:

var http = require('http');
var querystring = require('querystring');
 
var postHTML = 
  '<html><head><meta charset="utf-8"><title>菜鸟教程 Node.js 实例</title></head>' +
  '<body>' +
  '<form method="post">' +
  '网站名: <input name="name"><br>' +
  '网站 URL: <input name="url"><br>' +
  '<input type="submit">' +
  '</form>' +
  '</body></html>';
 
http.createServer(function (req, res) {
  var body = "";
  req.on('data', function (chunk) {
    body += chunk;
  });
  req.on('end', function () {
    // 解析参数
    body = querystring.parse(body);
    // 设置响应头部信息及编码
    res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});
 
    if(body.name && body.url) { // 输出提交的数据
        res.write("网站名:" + body.name);
        res.write("<br>");
        res.write("网站 URL:" + body.url);
    } else {  // 输出表单
        res.write(postHTML);
    }
    res.end();
  });
}).listen(3000);

--------------------------------------------Node.js 工具模块---------------------------------------
在 Node.js 模块库中有很多好用的模块。接下来我们为大家介绍几种常用模块的使用:

序号
模块名 & 描述

1
[**OS 模块**](http://www.runoob.com/nodejs/nodejs-os-module.html)提供基本的系统操作函数。

2
[**Path 模块**](http://www.runoob.com/nodejs/nodejs-path-module.html)提供了处理和转换文件路的工具。

3
[**Net 模块**](http://www.runoob.com/nodejs/nodejs-net-module.html)用于底层的网络通信。提供了服务端和客户端的的操作。

4
[**DNS 模块**](http://www.runoob.com/nodejs/nodejs-dns-module.html)用于解析域名。

5
[**Domain 模块**](http://www.runoob.com/nodejs/nodejs-domain-module.html)简化异步代码的异常处理,可以捕捉处理try catch无法捕捉的。

--------------------------------------------Node.js Web 模块--------------------------------
01、什么是 Web 服务器?
Web服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序,Web服务器的基本功能就是提供Web信息浏览服务。它只需支持HTTP协议、HTML文档格式及URL,与客户端的网络浏览器配合。
大多数 web 服务器都支持服务端的脚本语言(php、python、ruby)等,并通过脚本语言从数据库获取数据,将结果返回给客户端浏览器。
目前最主流的三个Web服务器是Apache、Nginx、IIS。
02、Web 应用架构

image.png
Client - 客户端,一般指浏览器,浏览器可以通过 HTTP 协议向服务器请求数据。
Server - 服务端,一般指 Web 服务器,可以接收客户端请求,并向客户端发送响应数据。
Business - 业务层, 通过 Web 服务器处理应用程序,如与数据库交互,逻辑运算,调用外部程序等。
Data - 数据层,一般由数据库组成。
03、使用 Node 创建 Web 服务器
Node.js 提供了 http 模块,http 模块主要用于搭建 HTTP 服务端和客户端,使用 HTTP 服务器或客户端功能必须调用 http 模块,代码如下:
var http = require('http');

以下是演示一个最基本的 HTTP 服务器架构(使用8081端口),创建 server.js 文件,代码如下所示:

var http = require('http');
var fs = require('fs');
var url = require('url');


// 创建服务器
http.createServer( function (request, response) {  
   // 解析请求,包括文件名
   var pathname = url.parse(request.url).pathname;
   
   // 输出请求的文件名
   console.log("Request for " + pathname + " received.");
   
   // 从文件系统中读取请求的文件内容
   fs.readFile(pathname.substr(1), function (err, data) {
      if (err) {
         console.log(err);
         // HTTP 状态码: 404 : NOT FOUND
         // Content Type: text/plain
         response.writeHead(404, {'Content-Type': 'text/html'});
      }else{             
         // HTTP 状态码: 200 : OK
         // Content Type: text/plain
         response.writeHead(200, {'Content-Type': 'text/html'});    
         
         // 响应文件内容
         response.write(data.toString());       
      }
      //  发送响应数据
      response.end();
   });   
}).listen(8081);

// 控制台会输出以下信息
console.log('Server running at http://127.0.0.1:8081/');

接下来我们在该目录下创建一个 index.htm 文件,代码如下:

<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>

执行 server.js 文件:

$ node server.js
Server running at http://127.0.0.1:8081/

04、使用 Node 创建 Web 客户端
Node 创建 Web 客户端需要引入 http 模块,创建 client.js 文件,代码如下所示:

var http = require('http');

// 用于请求的选项
var options = {
   host: 'localhost',
   port: '8081',
   path: '/index.htm'  
};

// 处理响应的回调函数
var callback = function(response){
   // 不断更新数据
   var body = '';
   response.on('data', function(data) {
      body += data;
   });
   
   response.on('end', function() {
      // 数据接收完成
      console.log(body);
   });
}
// 向服务端发送请求
var req = http.request(options, callback);
req.end();

05、使用 Node 创建 Web 客户端
Node 创建 Web 客户端需要引入 http 模块,创建 client.js 文件,代码如下所示

var http = require('http');

// 用于请求的选项
var options = {
   host: 'localhost',
   port: '8081',
   path: '/index.htm'  
};

// 处理响应的回调函数
var callback = function(response){
   // 不断更新数据
   var body = '';
   response.on('data', function(data) {
      body += data;
   });
   
   response.on('end', function() {
      // 数据接收完成
      console.log(body);
   });
}
// 向服务端发送请求
var req = http.request(options, callback);
req.end();

新开一个终端,执行 client.js 文件,输出结果如下:

$ node client.js
<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>

执行 server.js 的控制台输出信息如下:

Server running at http://127.0.0.1:8081/
Request for /index.htm received.   # 客户端请求信息

相关文章

  • 07、GET/POST请求 工具模块- Web 模块

    在很多场景中,我们的服务器都需要跟用户的浏览器打交道,如表单提交。表单提交到服务器一般都使用 GET/POST 请...

  • nodejs创建web服务器和Tcp服务器

    使用http模块创建Web服务器 Web服务器的功能: 接受HTTP请求(GET、POST、DELETE、PUT、...

  • python请求模块

    爬虫请求模块 urllib.request中的get与post请求 get请求,查询参数在url地址中显示head...

  • 深入了解xUtils

    xUtils分为四大模块: 网络模块:Post , get 请求数据 使用注解联网操作: 快速生成点击事件: ...

  • HttpUtil工具

    HttpUtil工具,http get post请求,https get post请求,ajax response...

  • python的flask模块 GET与POST 基础

    1.不传data,则为GET请求;传了data,则为POST请求。 2.python3中的urllib模块和req...

  • (十)接口自动化-requests模块其他请求形式

    requests模块除了发起常用的get和post请求之外,还可以发起其他类型的http请求方式,这些内容都在re...

  • requests库

    导入模块 使用requests库之前需要先导入模块。 发送请求 requests模块发出get请求,即可获取整个网...

  • Http请求工具类

    1. HTTP请求工具类 包含 GET、POST表单、POST Json、POST上传应用、GET下载应用

  • SuperAgent 的使用文档

    superagent是nodejs里一个非常方便的客户端请求代理模块,当你想处理get,post,put,dele...

网友评论

    本文标题:07、GET/POST请求 工具模块- Web 模块

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