设为首页 加入收藏

TOP

nodeJS之HTTP(七)
2017-10-13 10:50:15 】 浏览:6969
Tags:nodeJS HTTP
3. agent Defaults to https.globalAgent. callback <Function>

  向一个安全的服务器发起一个请求

  参数options可以是一个对象或是一个字符串。如果一个字符串,它自动被 url.parse()所解析

 

应用

【简单的GET请求】

var https = require('https');
https.get('https://www.cnblogs.com/', function(res){
    var data = '';
    res.setEncoding('utf8');
    res.on('data', function(chunk){
        data += chunk;
    });
    res.on('end', function(){
        console.log(data);
    });
});

【简单的POST请求】

var http = require('http');
var querystring = require('querystring');
var createClientPostRequest = function(){
    var options = {
        method: 'POST',
        protocol: 'http:',
        hostname: '127.0.0.1',
        port: '3000',
        path: '/post',
        headers: {
            "connection": "keep-alive",
            "content-type": "application/x-www-form-urlencoded"
        }    
    };
    // 发送给服务端的数据
    var postBody = {
        a: '1'
    };
    // 创建客户端请求
    var client = http.request(options, function(res){
        // 最终输出:Server got client data: nick=chyingp
        res.pipe(process.stdout);  
    });
    // 发送的报文主体,记得先用 querystring.stringify() 处理下
    client.write( querystring.stringify(postBody) );
    client.end();
};
// 服务端程序,只是负责回传客户端数据
var server = http.createServer(function(req, res){
    res.write('Server got client data: ');
    req.pipe(res);
});
server.listen(3000, createClientPostRequest);

 

<script type="text/java script" src="http://files.cnblogs.com/files/xiaohuochai/contextMenu.js"> <script type="text/java script" src="http://files.cnblogs.com/files/xiaohuochai/catalog.js">
首页 上一页 4 5 6 7 下一页 尾页 7/7/7
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇如何通过JS实现简单抖动效果 下一篇如何实现冒泡排序

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目