'Trying to get data from external api with basic authentication using node and https
I am trying to get data from an external api, which requires basic authentication. I am using node + express, and the https module.
I am not getting any errors, simply a 401 response status code, I just don't get to log in.
Also, on postman I do get the response without any problems. Which means that both the url and the authentication data I am passing are correct.
Really stuck here. Any help will be massively appreciated!
Manel
My code:
const express = require('express');
const https = require("https");
const basic = require('basic-authorization-header');
const app = express();
const auth = {
'Authorization': basic("username", "password"),
};
app.get("/", (req, res) => {
const url = "https://dictapi.lexicala.com/search?source=global&language=en&text=working&analyzed=true"
https.get(url, auth, (response) => {
console.log(response.statusCode);
console.log(auth);
response.responseType="text";
response.on("data", (data)=> {
const translationLot = JSON.parse(data)
console.log(translationLot);
})
})
res.send("Server is up and running")
});
const PORT = process.env.PORT || 7070;
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
Output on terminal:
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Server is running on port 7070
401
{ Authorization: 'Basic TW5M2FzOMQ==' }
{ status: 401, message: 'Not logged in' }
Solution 1:[1]
As i read in the docs
options.auth's type is string, so i suggest trying something like:
app.get("/", (req, res) => {
const url = "https://dictapi.lexicala.com/search?source=global&language=en&text=working&analyzed=true"
const options = {
auth : 'username:password' //here you put your credentials
}
https.get(url, options, (response) => {
console.log(response.statusCode);
console.log(auth);
response.responseType="text";
response.on("data", (data)=> {
const translationLot = JSON.parse(data)
console.log(translationLot);
})
})
res.send("Server is up and running")
});
I found the info here
Solution 2:[2]
Did you enter your actual username and password here?
basic("username", "password")
Replace username with your actual username and password with your actual password between the quotes.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sebas R. |
| Solution 2 | David Jorgensen |
