简体   繁体   English

在Node JS的python中,auth的等价物是什么?

[英]What is the equivalent of auth in python in Node JS?

I'm trying to access an api where I need to pass in the api key and the api secret but I'm doing it in Node JS. 我正在尝试访问api,我需要传递api密钥和api秘密但我在Node JS中这样做。 In Python you can do this: 在Python中,您可以这样做:

  requests.get('https://api.github.com/user', auth=('user', 'pass'));

My question is how do I accomplish this in Node JS? 我的问题是我如何在Node JS中实现这一目标? Do I include the key and secret in the header or include it in the options object? 我是否在标题中包含密钥和密钥或将其包含在选项对象中?

This is the code: 这是代码:

var options = {
  host:'linktowebsite',
  path:'/data',
  headers: {
' Content-Type': 'application/x-www-form-urlencoded'
}
};

var req = http.request(options, function(res) {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);

  res.setEncoding('utf8');
  res.on('data', (chunk) => {
  console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
 console.log('No more data in response.');
  });
});

req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});

Here it goes, 在这里,

var options = {
  host:'linktowebsite',
  path:'/data',
  headers: {
  'Content-Type': 'application/x-www-form-urlencoded',
  'Authorization' : "Basic " + new Buffer(username + ":" + password).toString("base64")
}
};

needle

const needle = require('needle');
let options = { username: 'user', password: 'pass' };
needle.get('https://api.github.com/user', options, (err, resp, body) => {
   // Whatever
})

request 请求

const request = require('request');
request.get('https://api.github.com/user', (err, resp) => {
   // Whatever
}).auth('username', 'password', false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM