In a Zapier Zap, I'm extracting data from Google Sheets and using JS to prettify it to later send in an email. I'm bumping into an error with the following message:
SyntaxError: Unexpected token ]
My code in zap
const data = {
"list_ids": [
"a0b30126-69d6-4822-ac06-bf76c3ff4770"
],
"contacts": [
{
"email": "email",
"first_name": "name",
"custom_fields": {
"e5_T": "list",
"e6_T": "y",
"e7_T": "z"
}
]
}
const res = await fetch('https://api.sendgrid.com/v3/marketing/contacts', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'authorization': 'Bearer <<my api key>>'
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
return { res };
I used code from this blog https://joelaguero.com/how-to-add-a-sendgrid-contact-with-zapier-code-snippets/. Author said it worked for him.
It's because you have more { than }.
You probably forgot about closing } in custom_fields or in contacts.
Related
I'm new to the FetchAPAI. For my first API project, I'm currently using the ClimatIQ API and following the steps in their Quickstart guide. Even if I've already signed up and received an authentication key from them, I keep getting the ff error from them:
POST https://beta2.api.climatiq.io/estimate 400
{error: 'invalid_request', message: 'Error parsing the request body.'}
Take note in the guide, the code is in Curl, and I did my best trying to convert that code into a fetchAPI request on JavaScript.
const fetchData = async (url) => {
await fetch(url, {
method: "POST",
headers: { Authorization: "Bearer MY_API_KEY" },
data: {
emission_factor: "electricity-energy_source_grid_mix",
parameters: {
energy: 4200,
energy_unit: "kWh",
},
},
//body: JSON.stringify(data),
})
.then((response) => response.json())
.then((json) => console.log(json))
.catch((err) => console.log(`Here's the error ${err}`));
};
fetchData("https://beta2.api.climatiq.io/estimate");
From time to time, it also shows a "header is not defined" even if I already put in the authentication key they gave me in the "MY_API_KEY" part of my codebase. Is this an error with their server?
try this:
const data = {
emission_factor: "electricity-energy_source_grid_mix",
parameters: {
energy: 4200,
energy_unit: "kWh",
},
};
const fetchData = async(url) => {
await fetch(url, {
method: "POST",
headers: {
Authorization: "Bearer MY_API_KEY",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then((response) => response.json())
.then((json) => console.log(json))
.catch((err) => console.log(`Here's the error ${err}`));
};
fetchData("https://beta2.api.climatiq.io/estimate");
I have a below code which is giving me response but when i try to access properties of the response, i am getting 'undefined'
const request = require('request-promise');
const option= {
method: 'GET',
uri: 'urihere',
qs: {
q: 'Mark'
},
json: true,
resolveWithFullResponse: true,
headers: {
'User-Agent': 'requestXYZPromise',
'Authorization': ''
}
}
request(option)
.then(response => {
})
.catch(error => {
})
What's wrong here? Please suggest.
Update - Response data. I am trying to get 'score'
{
"responseHeader":{
"ist":"json",
"version":"1.0"}},
"response":{"score":2,"start":0,"maxScore":18.9204}
}
Your response has itself a property called response. To access your score value you would need to call response.response.score.
{
"response": {
"score": 2,
"start": 0,
"maxScore": 18.9204
}
}
This is your response and you can access as below.
request(option)
.then(response => {
console.log(response.response.score)
})
.catch(error => {
})
I am not able to get accessToken, i need it in my backend api.
When i try this,
googleLogin = () => {
GoogleSignin.signIn()
.then((data) => {
console.log("TEST "+JSON.stringify(data));
var postData = {
access_token: data.accessToken,
code: data.idToken,
};
let axiosConfig = {
headers: {
'Content-Type': 'application/json',
"Accept": "application/json",
}
};
....
//Backend api axios call
....
})
.then((user) => {
console.log("TEST G LOGIN 1 "+JSON.stringify(user))
})
.catch((error) => {
console.log("....."+JSON.stringify(error))
});
}
got this response, it doesn't inculde
accessToken
{
"scopes": ["https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/drive.readonly"],
"serverAuthCode": "4/jwE5LLLLLLa7-f33333jmMD2V978oyp44444eb9yGe_qhHnkXXXXXXXLFXKZlQdDzlH-iIJx_gzqlLLLLLL3Q0PP0",
"idToken": "...v65a4MCC-ZUQmys_wf_DoCOBJEMuI........",
"user": {
"photo": "https://lh3.googleusercontent.com/-tLLLLLyeS0KE/AAAMMMMAAAI/AAAAAAAAAAA/ACHi3reMhihoeTe_6NjL666666EUVU82Q/s96-c/photo.jpg",
"email": "test#gmail.com",
"familyName": "tech",
"givenName": "test",
"name": "testtech",
"id": "11688888817288868"
}
}
as per documentation
getTokens() Resolves with an object containing { idToken: string,
accessToken: string, } or rejects with an error. Note that using
accessToken is discouraged.
So, i tried this in
GoogleSignin.Sign({
....
var gettoken = GoogleSignin.currentUserAsync(data.user).then((token) => {
console.log('USER token', token);
}).done();
...
})
it got error and also tried const token = GoogSignIn.getTokens(), it return null.
package.json info
{
...
"react": "16.8.3",
"react-native": "0.59.9",
"react-native-firebase": "5.3.1",
"react-native-google-signin": "^2.0.0"
...
}
Please suggest what would be procedure to get accessToken.
Finally i get accessToken.
Step 1:-
I deleted all the generated clidenId in goolge developer console (keep only web application clientId as i used in my web project) and also deleted android app in firebase project.
Step 2:-
Created new android app in firebase and download google-services.json and paste it in android/app/google-services.json
Step 3:-
Copied the clidenId from this part of google-services.json
...
"services": {
"appinvite_service": {
"other_platform_oauth_client": [
{
"client_id": "xxxxxxx-xxxxx.apps.googleusercontent.com", //<--- copied this clientID
"client_type": 3
},
{
"client_id": "XXXXXXXXXX-fBBBBBBBBBBBBBBBBBBBBBBBBpugnhrade.apps.googleusercontent.com",
"client_type": 2,
"ios_info": {
"bundle_id": "com.projectios"
}
}
]
}
}
...
and paste in
GoogleSignin.configure({
webClientId: 'paste it here',
});
Step 4:-
This is the code to get accessToken
(But this code was not working in my previous google-services.json file)
googleLogin = () => {
GoogleSignin.signIn()
.then((data) => {
console.log("TEST " + JSON.stringify(data));
const currentUser = GoogleSignin.getTokens().then((res)=>{
console.log(res.accessToken ); //<-------Get accessToken
var postData = {
access_token: res.accessToken,
code: data.idToken,
};
let axiosConfig = {
headers: {
'Content-Type': 'application/json',
"Accept": "application/json",
}
};
-----
backend api call
-----
});
})
.then((user) => {
console.log("TEST G LOGIN 1 " + JSON.stringify(user))
})
.catch((error) => {
console.log("....." + JSON.stringify(error))
});
}
I have a oauth set up. But when I want to get the access token with the fetch() function it just returns an object with things like _bodyInit, _bodyBlob and headers. So I just cannot get a JSON object. I'm on Android if that matters in any way.
Code:
componentDidMount() {
Linking.getInitialURL().then(url => {
if(url) {
console.log(url);
const queries = url.substring(16)
const dataurl = qs.parse(queries);
if(dataurl.state === 'ungessable15156145640!') {
console.log(dataurl.code);
console.log(dataurl.state);
return code = dataurl.code;
}
}
}).then((code) => {
fetch(`https://dribbble.com/oauth/token`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'client_id': 'MY_ID',
'client_secret': 'MY_SECRET',
'code': code
})
})
.then((res) => {
var access_token = res;
console.log(access_token);
});
});
}
You almost got it right, you are missing one step though!
fetch doesn't return a json object, it returns a Response object, in order to get the json object, you have to use res.json()
fetch(`https://dribbble.com/oauth/token`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'client_id': 'MY_ID',
'client_secret': 'MY_SECRET',
'code': code
})
})
.then((res) => {
return res.json();
})
.then((json) => {
console.log(json); // The json object is here
});
It's a good practice to add a catch just in case something goes wrong.
.then((json) => {
console.log(json); // The json object is here
});
.catch((err) => {
// Handle your error here.
})
I have a oauth set up. But when I want to get the access token with the fetch() function it just returns an object with things like _bodyInit, _bodyBlob and headers. So I just cannot get a JSON object. I'm on Android if that matters in any way.
Code:
componentDidMount() {
Linking.getInitialURL().then(url => {
if(url) {
console.log(url);
const queries = url.substring(16)
const dataurl = qs.parse(queries);
if(dataurl.state === 'ungessable15156145640!') {
console.log(dataurl.code);
console.log(dataurl.state);
return code = dataurl.code;
}
}
}).then((code) => {
fetch(`https://dribbble.com/oauth/token`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'client_id': 'MY_ID',
'client_secret': 'MY_SECRET',
'code': code
})
})
.then((res) => {
var access_token = res;
console.log(access_token);
});
});
}
You almost got it right, you are missing one step though!
fetch doesn't return a json object, it returns a Response object, in order to get the json object, you have to use res.json()
fetch(`https://dribbble.com/oauth/token`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'client_id': 'MY_ID',
'client_secret': 'MY_SECRET',
'code': code
})
})
.then((res) => {
return res.json();
})
.then((json) => {
console.log(json); // The json object is here
});
It's a good practice to add a catch just in case something goes wrong.
.then((json) => {
console.log(json); // The json object is here
});
.catch((err) => {
// Handle your error here.
})