How to GET json data from API with a header - express

I'm trying to get JSON data from an API using NodeJS and Express, but it requires a header I'm not sure how to input the header into the get request.
The documentation says:
curl -H"X-FullContact-APIKey:$your_key"
'https://api.fullcontact.com/v2/person.json?email=bart#fullcontact.com'
How do I do a add a get request with a header? I looked everywhere on Stackoverflow for days, and havent found anything. Everything is for PHP, nothing for NodeJS w/ Express. How can I do this with the Request Node NPM Manager Package

Not sure on how your request code looks like, but this should do it; right?
var request = require('request');
var options = {
url: 'https://api.fullcontact.com/v2/person.json?email=bart#fullcontact.com',
headers: {
'X-FullContact-APIKey': '$your_key'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var result = JSON.parse(body);
console.log(result);
}
}
request(options, callback);

Related

Unauthenticated requests are not allowed. Take out a new plan or start a free trial at https://pro.bitcoinaverage.com

I want to print BTC conversion to other currencies. I am using bitcoinaverage. On the browser, the URL is not working. The screen displays this "Unauthenticated requests are not allowed. Take out a new plan or start a free trial at https://pro.bitcoinaverage.com". I am using Flutter. On console, it is giving a 404 error. The following is the code snippet.
const bitcoinAverageURL = 'https://apiv2.bitcoinaverage.com/indices/average/ticker';
Future getCoinData(String selectedCurrency) async {
var authKey = '$bitcoinAverageURL/BTCAUD';
http.Response response = await http.get(Uri.parse(authKey));
if (response.statusCode == 200) {
var decodedData = jsonDecode(response.body);
double current = decodedData['last'];
return current.toStringAsFixed(0);
} else {
print(response.statusCode);
throw 'Problem with get request';
}
From documentation:
All requests to our API must be authenticated with your public key.
You need to autrhorize on API site and get your API access token. API usage described in Official documentation.
Try to add your API key to header:
await http.get(
Uri.parse(url),
headers: {
'x-ba-key': 'your_api_key',
},
);

Is there a way to execute XHR Requests via VS Code Extension?

I am building a VS Code extension and in that, I need to execute an XHR Request to my server to fetch some data.
I tried using this in my code :
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
vscode.window.showInformationMessage(this.responseText);
}
};
xhttp.open("GET", "https://reqres.in/api/users?page=2", true);
xhttp.send();
}
but it is showing an error :
Any idea, how can I achieve my goal?
XMLHttpRequest and fetch are only available in the browser. vsCode is node.js based. Use Axios instead. How can I make a POST request in a VSCode extension

RabbitMQ HTTP API returning 401 (Unauthorized)

Using RabbitMQ localhost and trying to use his API.. when i Call from postman it's work fine.
But i'm trying to use this API inside my app code and I'm getting 401 error:
const test = {
count: 5,
ackmode: 'ack_requeue_true',
encoding: 'auto',
truncate: 50000
}
testPost() {
fetch('http://localhost:15672/api/queues/%2F/QA.MOBILE/get', {
method: 'post',
mode: 'no-cors',
body: JSON.stringify(test),
headers: {Authorization: 'Basic ' + btoa('guest:guest'), Accept: 'application/json', 'Content-Type': 'application/json'}
});
}
POST http://localhost:15672/api/queues/%2F/QA.MOBILE/get net::ERR_ABORTED 401 (Unauthorized)
I'm missing something?
thanks
I just had this problem myself. Even though my issue was not CORS related, I thought I would document the issue here in case future readers have the same problem.
My issue was that I was not correctly base64ing the user credentials. From a browser you can just call any of the RabbitMQ API endpoints like this:
http://somename:somepassword#servername:15672/api/cluster-name
But when calling it programatically, you need to remove the credentials from the url and base 64 them instead.
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "http://servername:15672/api/cluster-name"))
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes($"somename:somepassword"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
var response = httpClient.SendAsync(request).Result;
if (response.IsSuccessStatusCode == true)
{
string jsonContent = response.Content.ReadAsStringAsync().Result;
}
}
}
The above code is C# but it would be the same process for Java, etc.

ionic 2: http get request not working (proxy added)

I'm using Http from #angular/http to send GET requests, but the server is not receiving the request. The generated urls are correct because when I log them and open them in browser (I've tried all of Chrome, Firefox and Safari), the server does receive these requests.
This is how I am doing this:
let logButtonUrl = this.urlGenerator.generateTiramisuUrlTemp(this.servletPath,
argMap);
console.log("logButtonUrl:"+logButtonUrl);
return this.http.get(logButtonUrl).map(this.writeSuccess);
Function writeSuccess:
private writeSuccess(res: Response) {
let body = res.json();
let rows_affected = body.data[0].rowsAffected;
if (rows_affected == "1") {
return true;
} else {
return false;
}
}
I got no error message in browser console, so it's probably not because of the CORS issue discussed here:
http://blog.ionic.io/handling-cors-issues-in-ionic/
I also tried using a proxy. I added this in ionic.config.json:
{
"path": "/backendTemp",
proxyUrl": "http://128.237.217.70:8080" /*the ip address of the target server*/
}
And replace the ip address in my generated urls with "/backendTemp". Still not working.
Any suggestions/thoughts on this? Thanks a lot!
Use the $http (https://docs.angularjs.org/api/ng/service/$http):
.controller('RequestCtrl', function ($http) {
$http({
method: 'GET',
url: 'http://128.237.217.70:8080/backendTemp'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

How do I write a Node.js request to 3rd party API?

Does anyone have an example of an API response being passed back from a http.request() made to a 3rd party back to my clientSever and written out to a clients browser?
I keep getting stuck in what I'm sure is simple logic. I'm using express from reading the docs it doesn't seem to supply an abstraction for this.
Thanks
Note that the answer here is a little out of date-- You'll get a deprecated warning. The 2013 equivalent might be:
app.get('/log/goal', function(req, res){
var options = {
host : 'www.example.com',
path : '/api/action/param1/value1/param2/value2',
port : 80,
method : 'GET'
}
var request = http.request(options, function(response){
var body = ""
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
res.send(JSON.parse(body));
});
});
request.on('error', function(e) {
console.log('Problem with request: ' + e.message);
});
request.end();
});
I would also recommend the request module if you're going to be writing a lot of these. It'll save you a lot of keystrokes in the long run!
Here is a quick example of accessing an external API in an express get function:
app.get('/log/goal', function(req, res){
//Setup your client
var client = http.createClient(80, 'http://[put the base url to the api here]');
//Setup the request by passing the parameters in the URL (REST API)
var request = client.request('GET', '/api/action/param1/value1/param2/value2', {"host":"[put base url here again]"});
request.addListener("response", function(response) { //Add listener to watch for the response
var body = "";
response.addListener("data", function(data) { //Add listener for the actual data
body += data; //Append all data coming from api to the body variable
});
response.addListener("end", function() { //When the response ends, do what you will with the data
var response = JSON.parse(body); //In this example, I am parsing a JSON response
});
});
request.end();
res.send(response); //Print the response to the screen
});
Hope that helps!
This example looks pretty similar to what you are trying to achieve (pure Node.js, no express):
http://blog.tredix.com/2011/03/partly-cloudy-nodejs-and-ifs.html
HTH