How to format axios GET call with nested params - axios

I want to fetch an API
The call look like this;
const instance = axios.create({
method: 'GET',
uri: 'https://api.compound.finance/api/v2/account',
timeout: timeout,
params: {
block_number:'0',
page_number:'1',
page_size:'250',
max_health: {
value:'1'
},
},
headers: {
"Content-Type": "application/json",
},
});
The API spec https://compound.finance/docs/api
{
"addresses": [] // returns all accounts if empty or not included
"block_number": 0 // returns latest if given 0
"max_health": { "value": "10.0" }
"min_borrow_value_in_eth": { "value": "0.002" }
"page_number": 1
"page_size": 10
}
However the output URI contains some character to replace { } arround max_health value
The uri end up looking like this;
/api/v2/account?block_number=0&page_number=1&page_size=250&max_health=%7B%22value%22:%221%22%7D'
I have tried qs but it's not working as I expect.
I have tryed this to ;
let params = {
block_number:'0',
page_number:'1',
page_size:'250',
max_health: {
value:'1'
}
}
await instance.get('https://api.compound.finance/api/v2/account',JSON.stringify(params)).then( (response) => {...})
It gave me this error ;
TypeError: Cannot use 'in' operator to search for 'validateStatus' in
{"block_number":"0","page_number":"1","page_size":"250","max_health":{"value":"1"}}
Any help would be appreciated.

The fix;
Use paramSerializer
const instance = axios.create({
method: 'GET',
uri: 'https://api.compound.finance/api/v2/account',
timeout: timeout,
params: {
block_number:'0',
page_number:'1',
page_size:'250',
max_health: {
value:'1'
},
},
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
headers: {
"Content-Type": "application/json",
},
});

Related

Axios, graphql: No 'Access-Control-Allow-Origin' header is present on the requested resource

Maybe it's duplicated anyway i've searched this specific case without finding anything related.
I'm working to plot a chart with tradingview and bitquery api using axios and graphql
The config of my query goes like this:
Bitquery.endpoint, {
query: Bitquery.GET_COIN_INFO,
variables: {
"tokenAddress": symbolName
},
mode: 'cors',
headers: {
"Content-Type": "application/json",
"X-API-KEY": "XXXXXXXXXXX",
"Access-Control-Allow-Origin" : "http://localhost:3000",
"Access-Control-Allow-Credentials" : "true",
"Access-Control-Allow-Methods" :" GET, POST, OPTIONS",
"Access-Control-Allow-Headers" : "Origin, Content-Type, Accept"
}
}
);
But i still receiving this error on console:
Access to XMLHttpRequest at 'https://graphql.bitquery.io/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Could someone give me a hint upon this? Thank you!
This query did worked:
const response = await fetch(
Bitquery.endpoint, {
method: 'POST',
headers: {
"Content-Type": "application/json",
"X-API-KEY": "XXXXXXXXXXXXXXXXXXXXXX"
},
variables: {
"tokenAddress": symbolName
},
mode: 'cors',
body: JSON.stringify({
query:`
{
ethereum(network: bsc) {
dexTrades(
options: {desc: ["block.height", "transaction.index"], limit: 1}
exchangeAddress: {is: "0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73"}
baseCurrency: {is: "0xe87e15b9c7d989474cb6d8c56b3db4efad5b21e8"}
quoteCurrency: {is: "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"}
)
{
block {
height
timestamp {
time(format: "%Y-%m-%d %H:%M:%S")
}
}
transaction {
index
}
baseCurrency {
name
symbol
decimals
}
quotePrice
}
}
}
`
})
}
)
.then((res) => res.json())
.then((result) => {return result})
// const coin = response.data.data.ethereum.dexTrades[0].baseCurrency;
// console.log(response.data.data.ethereum.dexTrades[0].quotePrice);
console.log(response);

How to return value from json-server on post request?

The issue
GET /api/get-request works correctly, and `{ x: 'x' } is returned to the frontend
POST /api/post-request works too but returns empty body
How I run json-server:
json-server src/configs/api/mocks/json-server-generator.js --routes src/configs/api/mocks/json-server-routes.json --watch"
json-server-routes.json
{
"/api/getrequest": "/getrequest",
"/api/postrequest": "/postrequest",
}
json-server-generator.js
module.exports = () => {
return {
getrequest: { x: 'x' },
postrequest: { y: 'y' }
}
}
Requests are made via fetch:
fetch(url, {
method,
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(payload)
})

How do I add auth headers to axios hooks requests?

I am working with React Hooks and I want to use the axios hooks package to send an image to Cloudinary.
const [
{ data: putData, loading: putLoading, error: putError },
executePut
] = useAxios(
{
url: 'https://api.myjson.com/bins/820fc',
method: 'PUT'
},
{ manual: true }
)
The docs say nothing about headers?
I believe you are looking for this:
const [
{ data: putData, loading: putLoading, error: putError },
executePut
] = useAxios(
{
url: 'https://api.myjson.com/bins/820fc',
method: 'PUT',
headers: {
'Content-Type': 'application/json'
}
},
{ manual: true }
)
docs: https://github.com/axios/axios#request-config

Unable to update Data

Am trying to update the json data through an api call.
I was able to GET the data without any issues, as am not passing any Options in the request.
For UPDATE,
//saga.js
export function* BlurideaTitler(opt) {
const id = opt.id; // 4
const updatedTitle = opt.newTitle; // "title changed"
let options = {
crossDomain: true,
method: 'PUT',
json: true,
headers: {'Content-Type': 'application/json'},
body: {
title: updatedTitle
}
};
const requestURL = `http://localhost:3000/ideas/${id}`;
try {
yield call(request, requestURL, options);
} catch (err) {
console.log(err);
}
}
// request.js
export default function request(url, options) {
return fetch(url, options)
.then(checkStatus)
.then(parseJSON);
}
//db.json
JSON am trying to update.,
{
"ideas": [
{
"id": 4,
"title": "My fourth Idea",
"body": "Description of my fourth idea",
"created_date": "14-Apr-2019"
}
]
}
This is supposed to update the value of title. But it throws error'Bad request' . Can someone please let me know what am missing here.

Is it possible to change the header config of an AngularJS $resource object?

Here's my code:
var userAuth;
var user = $resource('https://myservice.com/user/:id/', {id: '#_id'} ,{
login: {
method: 'POST',
params: {
id: 'login'
},
transformResponse: function(data) {
data = angular.fromJson(data);
userAuth = 'Kinvey '+data._kmd.authtoken;
return data;
}
},
current: {
method: 'GET',
params: {
id: '_me'
},
headers: {
'Authorization': userAuth
}
}
});
I want to be able to use the updated contents of the userAuth variable in the headers of the current endpoint of the resource, after it has been modified in the transformResponse of the login call. Is this even possible? If so, how?
EDIT: I am using Angular version 1.1.3 - this question is about changing the headers in the resource once they have been set, not settings them initially. Thanks
Assuming you are using the current stable release (1.0.8), although this feature is documented in the $resource page it has not been released.
AngularJS resource not setting Content-Type
EDIT:
See my comment below for the explaination of this code.
var customerHeaders = {
'Authorization' : ''
};
var user = $resource('https://myservice.com/user/:id/', {id: '#_id'} ,{
login: {
method: 'POST',
params: {
id: 'login'
},
transformResponse: function(data) {
data = angular.fromJson(data);
customHeaders.Authorization = 'Kinvey '+data._kmd.authtoken;
return data;
}
},
current: {
method: 'GET',
params: {
id: '_me'
},
headers: customHeaders
}
});