魏长东

weichangdong

东邪

nodejs 发get post请求

有时候在linux下,发送post一般用curl然后-d带上post数据,或者直接写php代码来发送请求。

用nodejs实现了下发送get和post请求。

post是向我的本地环境发送的,所以需要开启服务。node post 就OK。

var http = require("http");
http.createServer(function(req, res) {
	var body = [];
res.write(req.method);
//console.log(req.method);
    if(req.method == 'GET') {
		//res.write(res.query.toString());
		res.end("PATH: " + req.url);
	} else {
		//console.log(req.headers);
		req.on('data', function (chunk) {
			body.push(chunk);
		});

		req.on('end', function () {
			body = Buffer.concat(body);
			console.log(body.toString());
		});
	}
}).listen(8080);
console.log("HTTP server is listening at port 8080.");

发送请求的代码

var http = require("http");
var url = require("url");

var strUrl = "http://swordman.sinaapp.com";
http.get(strUrl, function(res){
    res.setEncoding("utf-8");
    var resData = [];
    res.on("data", function(chunk){
        resData.push(chunk);
    })
    .on("end", function(){
        console.log(resData.join(""));
    });
});

// 目标地址
strUrl = "http://localhost:8080/post";
var parse = url.parse(strUrl);

// 待发送的数据
var postStr = "username=www.zeroplace.cn&password=www.zeroplace.cn";
var options = {
    "method" : "POST",
    "host"   : parse.hostname,
    "path"   : parse.path,
    "port"   : parse.port,
    "headers": {
        "Content-Length" : postStr.length
    }
};
var req = http.request(options, function(res){
    res.setEncoding("utf-8");
    var resData = [];
    res.on("data", function(chunk){
        resData.push(chunk);
    }).on("end", function(){
        console.log(resData.join(""));
    });
});
req.write(postStr);
req.end();