2017-02-10 5 views
0

Ich versuche auf eine API zuzugreifen, wo ich den API-Schlüssel und das API-Geheimnis weitergeben muss, aber ich mache es in Knoten JS. In Python können Sie dies tun:Was entspricht in Python Auth in Knoten JS?

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

Meine Frage ist, wie kann ich das erreichen in Knoten JS? Schließe ich den Schlüssel und das Geheimnis in die Kopfzeile ein oder schließe sie in das Optionsobjekt ein?

Dies ist der 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}`); 
}); 

Antwort

1

Hier geht es,

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

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); 
+0

Gebrauchte Anfrage und es hat @Matt funktioniert – bkk