不太理解https.get()怎么加入headers?
发布于 8 年前 作者 smarttang 4568 次浏览 来自 问答

我看了下api貌似没有讲。。。

const https = require('https');

process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

https.get({host:'https://10.*.*.*:8183/',headers:{'user-agent':'fuckoude'}},(res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
  	console.log('..');
    // process.stdout.write(d);
  });

}).on('error', (e) => {
  console.error(e);
});
9 回复

@i5ting 认真的扫了一下,感觉这个跟我的需求不搭啊。。。我是在client发起请求,不是做webserver。。。

@smarttang 这样,你用request模块

https.request(options, callback)

const https = require('https');

var options = {
  hostname: 'encrypted.google.com',
  headers: {
    // 你要的header
  },
  port: 443,
  path: '/',
  method: 'GET'
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});
req.end();

req.on('error', (e) => {
  console.error(e);
});

https.get 本身就是对 https.request 方法的一个包装

@i5ting 额。。这个是异步的,我要同步请求。。。。

@wssgcg1213 这个也是异步请求。。。 虽然自己已经实现了,但是还是特别感谢你回复。。。 我的整个笔记在这:http://www.jianshu.com/p/dd5d6b77f1e7

同步请求和异步请求的本质没区别呀,用 promise 就搞定了。。。。

@wssgcg1213 这个模块在centos 6.5 安装不太友好。。

回到顶部