教程 > nodejs 教程 > 阅读:68

nodejs get/post请求——迹忆客-ag捕鱼王app官网

在很多场景中,ag捕鱼王app官网的服务器都需要跟用户的浏览器打交道,如表单提交。

表单提交到服务器一般都使用 get/post 请求。

本章节我们将为大家介绍 nodejs get/post请求。


获取get请求内容

由于get请求直接被嵌入在路径中,url是完整的请求路径,包括了?后面的部分,因此你可以手动解析后面的内容作为get请求的参数。

nodejs 中 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);

在浏览器中访问 http://localhost:3000/user?name=迹忆客&url=www.jiyik.com 然后查看返回结果:

node 服务 get参数

获取 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("name: "   params.name);
    res.write("\n");
    res.write("site url: "   params.url);
    res.end();
 
}).listen(3000);

在浏览器中访问 http://localhost:3000/user?name=jiyik&url=www.jiyik.com 然后查看返回结果:

node get 获取参数


获取 post 请求内容

post 请求的内容全部的都在请求体中,http.serverrequest 并没有一个属性内容为请求体,原因是等待请求体传输可能是一件耗时的工作。

比如上传文件,而很多时候我们可能并不需要理会请求体的内容,恶意的post请求会大大消耗服务器的资源,所以 node.js 默认是不会解析请求体的,当你需要的时候,需要手动来做。

基本语法结构说明

var http = require('http');
var querystring = require('querystring');
var util = require('util');
 
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);

以下实例表单通过 post 提交并输出数据:

实例

var http = require('http');
var querystring = require('querystring');
 
var posthtml = 
  '迹忆客 nodejs 实例'  
  ''  
  '
' 'webname:
' 'web url:
' '' '
' ''; 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("webname: " body.name); res.write("
"); res.write("web url: " body.url); } else { // 输出表单 res.write(posthtml); } res.end(); }); }).listen(3000);

执行结果 gif 演示:

node post 请求

查看笔记

扫码一下
查看教程更方便
网站地图