google People API error code: 400, Invalid JSON payload received - google-api-nodejs-client

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

Related

can't create cesium ion assets with from parameter

When I create an assets in cesium ion, I can not make it work if I use the from parameter.
this code is working, it create the assets and send back infos about the upload location.
axios.post('https://api.cesium.com/v1/assets', {
name: selectedFile.name,
description: '',
type: '3DTILES',
options: {
position:[ 2.29, 48.85, 0.1],
sourceType: srcType
}
},{
headers: { Authorization: `Bearer ${accessToken}` }
})
.then(response => assetCreated(response))
.catch(function (error) {
console.log(error);
});
But If I add the from parameter like this :
axios.post('https://api.cesium.com/v1/assets', {
name: selectedFile.name,
description: '',
type: '3DTILES',
options: {
position:[ 2.29, 48.85, 0.1],
sourceType: srcType
},
from: {
type:'S3',
bucket: 'mybucket',
credentials :{
accessKey:'key',
secretAccessKey:'secretkey'
}
}
},{
headers: { Authorization: `Bearer ${accessToken}` }
})
.then(response => assetCreated(response))
.catch(function (error) {
console.log(error);
});
Then I get "Request failed with status code 400".
From what I understand from the documentation (https://cesium.com/learn/ion/rest-api/#operation/postAssets) this should work though.
What am I doing wrong ?
Thanks for the help.

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

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

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.

Can make post request to localhost using node-fetch, but unable to do so using Axios

I have tried making the same post request using node-fetch and axios.
var fetch = require('node-fetch');
var axios = require('axios');
async function fetchTest(host, port, body) {
const response = {
successMessage: '',
errorMessage: ''
}
try {
const streamResponse = await fetch(`${host}:${port}`, {
method: 'post',
body: JSON.stringify(body)
})
const jsonResponse = await streamResponse.json()
response.successMessage = jsonResponse;
} catch (error) {
response.errorMessage = error;
}
return response;
}
async function axiosTest(host, port, body) {
const response = {
successMessage: '',
errorMessage: ''
}
try {
const jsonResponse = await axios({
method: 'post',
url: `${host}:${port}`,
data: body
})
response.successMessage = jsonResponse;
} catch (error) {
response.errorMessage = error;
}
return response;
}
async function test() {
console.log(await fetchTest('http://127.0.0.1', '8801', { type: 'request', cmd: 'devices' }));
console.log(await axiosTest('http://127.0.0.1', '8801', { type: 'request', cmd: 'devices' }));
}
test();
The request made with node-fetch works nicely. The request made with axios returns (IP address redacted with ...) an error:
{ successMessage: '',
errorMessage:
{ Error: connect ECONNREFUSED ...:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1161:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '...',
port: 80,
config:
{ adapter: [Function: httpAdapter],
transformRequest: [Object],
transformResponse: [Object],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
headers: [Object],
method: 'post',
url: 'http://127.0.0.1:8801',
data: '{"type":"request","cmd":"devices"}' },
request:
Writable {
_writableState: [WritableState],
writable: true,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_redirectCount: 1,
_redirects: [],
_requestBodyLength: 39,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [ClientRequest],
_currentUrl: 'http://.../',
_isRedirect: true },
response: undefined } }
What might be the reason? Am I doing something wrong?
EDITED with more info requested in comment:
The axios request fails the same way if I comment out the node-fetch request.
The node-fetch request returns:
{
cmd: 'devices',
payload: { devices: [Array] },
type: 'response' },
}
Since I wrap the result in a response object, the console.log looks like
{
successMessage:
{
cmd: 'devices',
payload: { devices: [Array] },
type: 'response'
},
errorMessage: ''
}