How to rewrite this cURL command to axios code - node.js

I need to call the propublica API the call example they have is using cURL:
-H "X-API-Key: PROPUBLICA_API_KEY"
How can i rewrite it in axios.
I tried this and does not work, get an undefined response.
axios.get('"https://api.propublica.org/congress/v1/members/{house}/{FL}/current.json/X-API-Key/APIKEY '),
]).then(axios.spread((response1, response2) => {
console.log(response1.data.url);
})).catch(error => {
console.log(error);
}); ```

the -H option is to pass the option as a header, not as a query parameter or as a part of the URL. You would have to do something like this instead:
axios.get(url, { headers: { 'X-API-Key': headerKey } })

Using the RESTClient Extension for firefox, this worked for me:
https://api.propublica.org/congress/v1/116/senate/members.json
with in Header X-API-Key:my-personal -key.
So using axios, you may use:
let url = 'https://api.propublica.org/congress/v1/116/senate/members.json';
axios.get(url,
{
headers: {
'X-API-Key': headerKey
}
}
)
.then (res=>console.log(res))
.catch(err => console.log(err));

This is working, thanks for the answers.
const axios = require('axios');
axios.request({
url: "https://api.propublica.org/congress/v1/members/house/FL/current.json",
headers: { 'X-API-Key': "API-KEY" },
method: 'get'
}).then(response => {
// console.log(response.data.url);
console.log(response.data)
}).catch(error => {
console.log(error);
});

Related

Difficulty with receiving data from axios get request

I'm running into some problems with my axios get request. I'm trying to fetch stock information using the TwelveData API. Here is my code:
const axios = require('axios');
require('dotenv').config()
const getTickerList = async() => {
await axios.get(`https://api.twelvedata.com/stocks?apikey=${process.env.API_KEY}&symbol=AAPL&country=US`).then(response => console.log(response.data));
}
When I execute that code, I get a really strange data response that I have attached: link to pic
I would appreciate any help or advice - thanks!
I have outlined the problem above: expected something not like that.
This is a known bug in Axios. The fix for now is to pin your Axios version to 1.1.3.
const axios = require("axios");
const options = {
method: 'GET',
url: 'https://twelve-data1.p.rapidapi.com/stocks',
params: {exchange: 'NASDAQ', format: 'json'},
headers: {
'X-RapidAPI-Key': 'SIGN-UP-FOR-KEY',
'X-RapidAPI-Host': 'twelve-data1.p.rapidapi.com'
}
};
const getTickerList = async() => {
axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});
}
In v1.2.1, it is fixed this error.
Try this
const getTickerList = async() => {
await axios.get(`https://api.twelvedata.com/stocks?apikey=${process.env.API_KEY}&symbol=AAPL&country=US`,
{
headers: {
'Accept-Encoding': 'application/json',
}
}).then(response => console.log(response.data));
}

An problem occur when submit a GET Request by node-fetch

I am using node-fetch to fetch data from REST API.
Here is my code:
this.getUserList = async (req, res) => {
const fetch = require('node-fetch');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
let params = {
"list_info": {
"row_count": 100
}
}
fetch('https://server/api/v3/users?input_data=' + JSON.stringify(params), {
headers:{
"TECHNICIAN_KEY": "sdfdsfsdfsd4343323242324",
'Content-Type': 'application/json',
},
"method":"GET"
})
.then(res => res.json())
.then(json => res.send(json))
.catch(err => console.log(err));
}
It works fine.
However, if I change the following statement:
let params = {"list_info":{"row_count": 100}}
To
let params = {"list_info":{"row_count": 100}, "fields_required": ["id"]}
It prompts the following error message:
FetchError: invalid json response body at https://server/api/v3/users?input_data=%7B%22list_info%22:%7B%22row_count%22:100%7D,%22fields_required%22:[%22id%22]%7D reason: Unexpected end of JSON input`
The problem is that you are not URL-encoding your query string. This can be easily accomplished using URLSearchParams.
Also, GET requests do not have any request body so do not need a content-type header. GET is also the default method for fetch()
const params = new URLSearchParams({
input_data: JSON.stringify({
list_info: {
row_count: 100
},
fields_required: ["id"]
})
})
try {
// 👇 note the ` quotes
const response = await fetch(`https://server/api/v3/users?${params}`, {
headers: {
TECHNICIAN_KEY: "sdfdsfsdfsd4343323242324",
}
})
if (!response.ok) {
throw new Error(`${response.status}: ${await response.text()}`)
}
res.json(await response.json())
} catch (err) {
console.error(err)
res.status(500).send(err)
}

Converting Curl to Nodejs Axios - Obtaining an Access Token

I am currently using curl in order to obtain an access token so I can consume an api with said token. The curl command I use is as follows:
curl --user <client_id>:<client_secret> https://api.ed-fi.org/v3/api/oauth/token --data 'grant_type=client_credentials'
It works and all...but instead of curling I want to utilize the axios library to get this access token instead.
Here's what I have but it doesn't work.
const buff = new Buffer.from('<client_id>:<client_secret>';
const base64data = buff.toString('base64');
axios({
method: 'POST',
url: 'https://api.ed-fi.org/v3/api/oauth/token',
headers: {
Authorization: `Basic ${base64data}`
},
data: { 'grant_type': 'client_credentials' }
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
I can't figure out what I'm missing or doing wrong?
You should change Content-Type (default for axios is JSON) and pass body just like you did in case of curl:
axios({
method: 'POST',
url: 'https://api.ed-fi.org/v3/api/oauth/token',
headers: {
Authorization: `Basic ${base64data}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
data: 'grant_type=client_credentials'
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});

'Axios' show Error: Network Error on server returning with 200 http status

I am using axios: "^0.19.0" to create get and post requests in react-native 0.60.4, but even after backend returning HTTP status code 200 axois showing Error: Network Error. Working perfectly on iOS but not on Android.
My request:
export default function uploadImageWithData(formData, url = "createGroup") {
return new Promise((resolve, reject) => {
axios({
method: "post",
url: BASEURL + "api/webservice/" + url,
data: formData,
headers: {
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${global.authToken}`
}
})
.then(response => {
resolve(response);
})
.catch(err => {
console.log("error: ", err);
reject(err);
});
});
}
Kindly help.
The issue with formData, in formData empty array appending in formData causing the issue(For Android).

How can I correctly make the fetch api call in react?

I wanted to fetch the result from the dummy API with react js using fetch. But I'm getting the error of "SyntaxError: Unexpected token < in JSON at position 0" from console.log()
handleSubmit(event) {
fetch({
url:'http://dummy.restapiexample.com/api/v1/employees',
mode: 'cors',
method: 'GET',
dataType: 'json',
headers: {
'Access-Control-Allow-Origin':'*',
'Content-Type': 'multipart/form-data'
}
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
event.preventDefault();
}
Fetch's first argument is 'url' and second argument is 'options'.Try out this one:
handleSubmit(event) {
fetch('http://dummy.restapiexample.com/api/v1/employees', {
mode: 'cors',
method: 'GET',
dataType: 'json',
headers: {
'Access-Control-Allow-Origin':'*',
'Content-Type': 'multipart/form-data'
}
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
event.preventDefault();
}
Seems like you are getting 404 response which is giving error while converting to json.
I have printed response before converting to json in below code. Check your console after running code.
fetch({
url:'http://dummy.restapiexample.com/api/v1/employees',
mode: 'cors',
method: 'GET',
dataType: 'json',
headers: {
'Access-Control-Allow-Origin':'*',
'Content-Type': 'multipart/form-data'
}
})
.then(response => {
console.log(response);
response.json()})
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
I usually get this error when I have a problem on the backend. Check if on the backend your API is returning the data in a json format.
Here is the updated one
fetch('http://dummy.restapiexample.com/api/v1/employees')
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log("result",data);
});
The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
I would prefer to use with Axios as its best recommended and suited for react applications.
axios.get( 'http://dummy.restapiexample.com/api/v1/employees')
.then( response => {
console.log("result",response.data)
} )
.catch( error => {
console.log("error",error)
} );
This happens when you make a request to the server and parse the response as JSON, but it’s not JSON.
fetch('http://dummy.restapiexample.com/api/v1/employees').then(res => res.json())
The actual request worked fine. It got a response. But the res.json() is what failed.
Read this for more suggestion

Resources