nodejs中发送https请求怎么设置请求头
答案:2 悬赏:30
解决时间 2021-12-14 01:40
- 提问者网友:心裂
- 2021-12-13 08:31
nodejs中发送https请求怎么设置请求头
最佳答案
- 二级知识专家网友:猖狂的痴情人
- 2021-12-13 09:33
用URL.openConnection()得到一个URLConnection对象,然后用URLConnection.setRequestProperty()来设置头信息
全部回答
- 1楼网友:何以畏孤独
- 2021-12-13 10:34
在web项目中,有时需要通过协议调取来自其他环境的数据。https是一种应用于安全数据传输的网络协议。我们都知道ajax可以异步请求数据,但单单通过ajax无法实现跨域。采用一些其他方式需要根据不同的浏览器做相应处理,火狐,谷歌等和ie需要各自做相应判断,所以这种通过浏览器来解析数据虽然省略了数据的解压缩等处理,但是在有安全认证等情况下做跨域处理确比较困难。比如:ie的请求header无法更改。这时通过node请求并解析数据就显得比较简单了。如下是nodejs中通过https请求数据的全过程:
var https = require('https');
var zlib = require('zlib');
var post_data="………………";//请求数据
var reqdata = json.stringify(post_data);
var options = {
hostname: '10.225.***.***',
port: '8443',
path: '/data/table/list',
method: 'post',
rejectunauthorized: false,
requestcert: true,
auth: 'admin:123456************',
headers: {
'username': 'admin',
'password': '123456************',
'cookie': 'locale=zh_cn',
'x-buildtime': '2015-01-01 20:04:11',
'autologin': '4',
'accept-encoding': 'gzip, deflate',
'x-timeout': '3600000',
'content-type': 'application/json',
"content-length":reqdata.length
}
};
var req = https.request(options, function (res) {
});
req.write(reqdata);
req.on('response', function (response) {
switch (response.headers['content-encoding']) {
case 'gzip':
var body = '';
var gunzip = zlib.creategunzip();
response.pipe(gunzip);
gunzip.on('data', function (data) {
body += data;
});
gunzip.on('end', function () {
var returndatatojson= json.parse(body);
req.end();
});
gunzip.on('error', function (e) {
console.log('error' + e.tostring());
req.end();
});
break;
case 'deflate':
var output = fs.createwritestream("d:temp.txt");
response.pipe(zlib.createinflate()).pipe(output);
req.end();
break;
default:req.end();
break;
}
});
req.on('error', function (e) {
console.log(new error('problem with request: ' + e.message));
req.end();
settimeout(cb, 10);
});
注:options,需要有请求数据的长度,options需要加上'accept-encoding': 'gzip, deflate',返回的数据需要判断是哪种压缩方式,然后解压缩获取到数据。gunzip的end事件里的returndatatojson即是获取的数据。
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯