Nodejs 初学http的get,post请求

对于http的get,post请求的区别,我的理解有下面两点:

1:get是向服务器索取数据的一种请求,而post是像服务器提交的一种请求。
2:post更加安全些,适合于登录,获取验证码等等。
3:post请求是将请求参数以form表单的形式post出去,而get请求参数直接加在path后面  例子 path="callme/index.cfm/userService/command/search?"+"lat=123&lon=123"

http的get请求代码如下:

var http = require('http');
var querystring = require('querystring');
var options = {
        host: 'xxx', // 这个不用说了, 请求地址
        port:80,
        path:path, // 具体路径, 必须以'/'开头, 是相对于host而言的
        method: 'GET', // 请求方式, 这里以post为例
        headers: { // 必选信息, 如果不知道哪些信息是必须的, 建议用抓包工具看一下, 都写上也无妨...
            'Content-Type': 'application/json'
        }
    };
    http.get(options, function(res) {
        var resData = "";
        res.on("data",function(data){
            resData += data;
        });
        res.on("end", function() {
            callback(null,JSON.parse(resData));
        });
    })

http的post请求代码如下

var http = require('http');
var querystring = require('querystring');
//json转换为字符串
var data = querystring.stringify({
    id:"1",
    pw:"hello"
});
var options = {
    host: '115.29.45.194',
//    host:'localhost',
//    port: 14000,
//    path: '/v1?command=getAuthenticode',
    path:'/callme/index.cfm/userService/command/getAuthenticode/',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(data)
    }
};

var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
    res.on('end',function(chunk){
        console.log("body: " + chunk);
    })
});
req.write(data);
req.end();

推荐大家用个google的一个应用:chrome-extension://aejoelaoggembcahagimdiliamlcdmfm/HttpClient.html
这个应用就是类似1个测试http的get,post请求的客户端。

以上songzm个人总结,如有错漏请指出。

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 137,434评论 19赞 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 181,143评论 25赞 708
  • 引言 HTTP协议我想任何IT人士都耳熟能详了,大家都能说出个所以然来。但是如果我问你HTTP协议的请求方法有哪些...
    拉肚阅读 2,050评论 0赞 14
  • 徐风拂暖舒蛮腰 翠滴新吐满芽梢 杨柳不识人间季 遍洒白雪染春苗 二零一七年初春于帝都
    Decem_Ray阅读 256评论 1赞 1
  • 风雨欲来风满楼 风停云散何时休 若想一日心花放 还需上下苦索求
    单双眼星人阅读 187评论 0赞 0

友情链接更多精彩内容