将具有基本身份验证的GET HTTPS请求发送到API

时间:2020-05-09 17:21:27

标签: javascript node.js api https get

我正在尝试将GET请求发送到受用户/密码保护的API。我正在使用Javascript,并添加了“身份验证”选项。

const https = require('https');

const headers= {
    'Accepts' : 'application/json',
}

const options = {
  hostname: 'api.com/more/info',
  port: 443,
  path: '/',
  auth: 'username:password',
  method: 'GET'
};

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

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

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

运行此代码时收到的错误是:

Error: getaddrinfo ENOTFOUND api/com/more/info
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26) {
  errno: -3008,
  code: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'api.com/more/info'
}

主机名已更改为匿名。

我在做什么错了?

在此先感谢您的任何建议。

1 个答案:

答案 0 :(得分:1)

'api.com/more/info'可能不是您的主机名。

尝试使用以下选项:

const options = {
  hostname: 'api.com',
  port: 443,
  path: '/more/info',
  auth: 'username:password',
  method: 'GET'
};