欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

nodejs 使用http进行post或get请求的实例(携带cookie)

程序员文章站 2023-09-01 18:32:14
安装http nmp install http 函数封装(可直接拿去进行使用) var http = require('http'); fu...

安装http

nmp install http

函数封装(可直接拿去进行使用)

var http = require('http');

function nodepostgetrequest(host, port, method, bodydata, callbackfunction, path, cookie) {
  //把将要发送的body转换为json格式 
 var body = bodydata;
 var bodystring = json.stringify(body);
  //http 头部
 var headers = {
'content-type': 'application/json',
'content-length': bodystring.length,
'cookie': cookie
 };

//用与发送的参数类型
var options = {
host: host,  //ip
port: port,   //port
path: path,   //get方式使用的地址
method: method, //get方式或post方式
headers: headers
  };
  var req = http.request(options, function(res) {
res.setencoding('utf-8');

var responsestring = '';

res.on('data', function(data) {
  responsestring += data;
});

res.on('end', function() {
  //这里接收的参数是字符串形式,需要格式化成json格式使用
  var resultobject = json.parse(responsestring);
  console.log('-----resbody-----', resultobject);
  callbackfunction(responsestring);
});

req.on('error', function(e) {
  // todo: handle error.
  console.log('-----error-------', e);
});
 });
 req.write(bodystring);
req.end();
}

nodepostgetrequest函数解析(使用方法)

host:ip地址
port:端口号
method:请求方式(get或post)
bodydata:进去时发送的内容(当为get请求时可以传null。)
callbackfunction:回调函数(请求发送后进行数据接收。需要自己实现对数据的处理)
path:请求路径(post请求可以为空。get不可为空)
cookie:需要携带的cookie

使用案例

  var datapost = {
  "body": {
    "header": {

    },
    "body": {

    }
  }
};

nodepostgetrequest(host, port, "post", datapost, detalcall, '', mycookie);

或

 var path = "";
nodepostgetrequest(host, port, "get", "", dealcallback, path, mycookie);

以上这篇nodejs 使用http进行post或get请求的实例(携带cookie)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。