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

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

Related

google People API error code: 400, Invalid JSON payload received

Hi guys am working on a projet the uses google people API to do crud operation on an authentiated user using nodejs and express server.
I was able to get all contacts, search for a particular contact and using the resoureName.
but i'm unable to create contact group or label. i have read google documentation for weeks, i am having error
here isresponse from the server
^
GaxiosError: Invalid JSON payload received. Unknown name "contactGroup[name]": Cannot bind query parameter. Field 'contactGroup[name]' could not be found in request message. at Gaxios. (D:#001ADeveloperZone\workSpaces\autmarket\node_modules\gaxios\build\src\gaxios.js:73:27)
at Generator.next ()
at fulfilled (D:#001ADeveloperZone\workSpaces\autmarket\node_modules\gaxios\build\src\gaxios.js:16:58)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
response: {
config: {
access_token: ',
refresh_token: '',
url: 'https://people.googleapis.com/v1/contactGroups?contactGroup%5Bname%5D=hotmail',
method: 'POST',
paramsSerializer: [Function (anonymous)],
headers: {
'Accept-Encoding': 'gzip',
'User-Agent': 'google-api-nodejs-client/0.7.2 (gzip)',
Authorization: '',
Accept: 'application/json'
},
params: [Object: null prototype] { contactGroup: { name: 'hotmail' } },
validateStatus: [Function (anonymous)],
responseType: 'json'
},
data: {
error: {
code: 400,
message: Invalid JSON payload received. Unknown name "contactGroup[name]": Cannot bind query parameter. Field 'contactGroup[name]' could not be found in request message.,
errors: [
{
message: Invalid JSON payload received. Unknown name "contactGroup[name]": Cannot bind query parameter. Field 'contactGroup[name]' could not be found in request message.,
reason: 'invalid'
}
],
status: 'INVALID_ARGUMENT',
details: [
{
'#type': 'type.googleapis.com/google.rpc.BadRequest',
fieldViolations: [Array]
}
]
}
},
headers: {
'alt-svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"',
'cache-control': 'private',
connection: 'close',
'content-encoding': 'gzip',
'content-type': 'application/json; charset=UTF-8',
date: 'Tue, 08 Mar 2022 16:27:38 GMT',
server: 'ESF',
'transfer-encoding': 'chunked',
vary: 'Origin, X-Origin, Referer',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-xss-protection': '0'
},
status: 400,
statusText: 'Bad Request'
},
config: {
access_token: ,
refresh_token: '',
url: 'https://people.googleapis.com/v1/contactGroups?contactGroup%5Bname%5D=hotmail',
method: 'POST',
paramsSerializer: [Function (anonymous)],
headers: {
'Accept-Encoding': 'gzip',
'User-Agent': 'google-api-nodejs-client/0.7.2 (gzip)',
Authorization: '',
Accept: 'application/json'
},
params: [Object: null prototype] { contactGroup: { name: 'hotmail' } },
validateStatus: [Function (anonymous)],
responseType: 'json'
},
code: 400,
errors: [
{
message: Invalid JSON payload received. Unknown name "contactGroup[name]": Cannot bind query parameter. Field 'contactGroup[name]' could not be found in request message.,
reason: 'invalid'
}
]
}
here is my code
create_group: (req, res) => {
try {
//create group or label
let userGoogleContactsGroups = getGroups().then((data) =>
JSON.parse(JSON.stringify(data))
);
let userGroups = userGoogleContactsGroups.then(({ contactGroups }) => {
let names = contactGroups.map((group) => `${group.name}`);
return names;
});
userGroups.then((data) => {
if (data.includes("amazoggn")) {
return res.status(301).json({ code: 301, mesage: "group exist" });
} else {
// let name =" amazoggn";
try {
contactGroup={
name:name
}
let strdata = JSON.parse(JSON.stringify({contactGroup}));
let mydata = people.contactGroups.create(strdata)
if (mydata) {
console.log(mydata)
} else {
return "error occured"
}
} catch (error) {
console.log(error)
}
}
});
} catch (error) {
console.log(error);
}
}
please I need help on this how do you create contact group in google people api
Looking at the docs I think you should specify a field requestBody in the call to people.contactGroups.create.
Try something like this:
const res = await people.contactGroups.create({
requestBody: {
"contactGroup": {
"name": "HelloWorld"
}
}
});

Nuxt proxy target not taken into account

When calling an api like below with Axios in Nuxt:
async test() {
await this.$axios
.post(
'https://webservice.foo.com/api-entreprise/enroler/?id=1234',
{ cle_authentification: '1qaz#WSX' }
// {
// headers: { 'Access-Control-Allow-Origin': '*' },
// withCredentials: false,
// }
)
.then((res) => {
console.log(res)
})
.catch((error) => {
console.log(error)
})
},
I'm getting the CORS error below in my browser:
Access to XMLHttpRequest at 'https://webservice.foo.com/api-entreprise/enroler/?id=1234' from origin 'http://mywebsite.test:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
So, I retried with proxy settings:
nuxt.config.js:
axios: {
proxy: true,
},
proxy: {
'/api123/': {
target:
'https://webservice.foo.com/api-entreprise/enroler/?id=1234',
pathRewrite: { '^/api123/': '' },
changeOrigin: true,
},
},
and the call below:
async test() {
await this.$axios
.post(
'/api123/',
{ cle_authentification: '1qaz#WSX' }
// {
// headers: { 'Access-Control-Allow-Origin': '*' },
// withCredentials: false,
// }
)
.then((res) => {
console.log(res)
})
.catch((error) => {
console.log(error)
})
},
But the proxy target doesn't seem to be used, and I get an error 400 showing http://mywebsite.test:3001/api123/ instead.
Request URL: http://mywebsite.test:3001/api123/
Request Method: POST
Status Code: 400 Bad Request
Remote Address: 127.0.0.1:3001
Referrer Policy: strict-origin-when-cross-origin
What's wrong in my proxy configuration ?
ref. https://axios.nuxtjs.org/options/#proxy

Why does the result of http request return an empty array?

I've tried using axios and fetch to get data from an API endpoint, but turns out to have only returned an empty array. It works fine in Postman. What have I missed?
Using Axios
axios({
method: "get",
url: "/api/purchase/receivegoods/index?action=detail-grn",
params: {
goods_receive_id: 71,
},
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
})
.then((response) => {
console.log(("response", response));
})
.catch((error) => {
console.log("error message: ", error.message);
});
Using Fetch
fetch(
"https://devactive.com/api/purchase/receivegoods/index?action=detail-grn",
{
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
params: {
goods_receive_id: 71,
},
}
)
.then((response) => response.json())
.then((result) => {
console.log("Success:", result);
})
.catch((error) => {
console.error("Error:", error);
});
EDIT:
The request is in JSON format. It looks like this (this is an example of an existing id:
{
"goods_receive_id" : 71
}
check for possible proxy configuration, postman uses system proxy by default.
You are not passing the data as the body when using Axios or Fetch. You are hitting the endpoint though. Try something like this:
data = {
"goods_receive_id" : 71
}
axios({
method: "get",
url: "/api/purchase/receivegoods/index?action=detail-grn",
data: JSON.stringify(data), // <- You add the data to the body here
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
})
.then((response) => {
console.log(("response", response));
})
.catch((error) => {
console.log("error message: ", error.message);
});
or
data = {
"goods_receive_id" : 71
}
fetch(
"https://devactive.com/api/purchase/receivegoods/index?action=detail-grn",
{
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
data: JSON.stringify(data), // <- You add the data to the body here
}
)
.then((response) => response.json())
.then((result) => {
console.log("Success:", result);
})
.catch((error) => {
console.error("Error:", error);
});

GitHub GraphQL keeps returning POST https://api.github.com/graphql 401 error

I have been trying for hours to fetch the data of some of my repositories but I keep getting this error
'POST https://api.github.com/graphql 401'
My Code
const githubData = {
token: "my token",
username: "mikechibuzor",
};
const body = {
query: `query {
user(login: "mikechibuzor"){
bio,
avatarUrl,
repositories(first: 20, orderBy: {field: CREATED_AT, direction: DESC}){
nodes{
name,
description,
forkCount,
languages(first: 100){
nodes{
name
}
}
}
}
}
}`,
};
const baseUrl = "https://api.github.com/graphql";
const headers = {
'Authorization': 'bearer ' + githubData.token,
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
};
fetch(baseUrl, {
method: "POST",
Headers: headers,
body: JSON.stringify(body),
mode: "cors",
})
.then((response) => response.json())
.then((data) => console.log(data.data))
.catch((err) => console.log(JSON.stringify(err)));
What am i not doing right?
Maybe just a typo – try the following:
fetch(baseUrl, {
method: "POST",
// lowercase 'h' for headers
headers: headers,
body: JSON.stringify(body),
mode: "cors",
})
// ...
In case that still doesn't work check your scopes for your access token. GitHub gives you detailed control about what kind of actions you want to allow with a specific token and what not.

How to format axios GET call with nested params

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",
},
});