Unexpected token < in JSON at position 4 - when fetch link Ajax [GAS] - json

First, I have to apologize for my poor English skill I am using Google Apps Script.
I'm trying to get JSON data from AJAX link but sometimes error occurs
Unexpected token < in JSON at position 4
I know the problem here is the data return form "HTML" while i expect "JSON"
I trying
My Script
async function getJSON () {
const myHeaders = {
'cache' : 'no-cache',
'pragma': 'no-cache',
'Cache-Control': 'no-cache',
'accept': 'text',
'dataType' : 'text',
'contentType': 'application/json; charset=utf-8',
};
const myInit = {
muteHttpExceptions: true,
method: 'GET',
headers: myHeaders,
};
const url = "https://www.xxxx.xxx/xxxxxxx/?ajax=xxxxxxx"
const content = await UrlFetchApp.fetch(url ,myInit).getContentText();
const obj = JSON.parse(content);
....
...
}

The problem as you say is that sometimes the response is an HTML, which generates that when the JSON.parse function is called, an error arises because the response does not contain a valid JSON.
This error comes from the server, so there is not much you can do about it. One way to handle the error is with a try-catch block, which is common practice in asynchronous fetch.
For example:
async function getJSON() {
try {
const myHeaders = {
'cache': 'no-cache',
'pragma': 'no-cache',
'Cache-Control': 'no-cache',
'accept': 'text',
'dataType': 'text',
'contentType': 'application/json; charset=utf-8',
};
const myInit = {
muteHttpExceptions: true,
method: 'GET',
headers: myHeaders,
};
const url = "https://www.xxxx.xxx/xxxxxxx/?ajax=xxxxxxx"
const content = await UrlFetchApp.fetch(url, myInit).getContentText();
const obj = JSON.parse(content);
// ...
} catch (err) {
console.log({
err
})
}
}

Related

How to save API Token to use later in Cypress test?

I have this code to use saved API token and use it on other test, but it doesn't work (I get this error message : Reference Error : access_token is not defined: so I need to save my generated token and use it on all my API test
const API_STAGING_URL = Cypress.env('API_STAGING_URL')
describe('Decathlon API tests', () => {
it('Get token',function(){
cy.request({
method:'POST',
url: 'https://test.com/as/token.oauth2?grant_type=client_credentials',
headers:{
authorization : 'Basic 1aFJueHkxddsvdvsdcd3cSA=='
}}).then((response)=>{
expect(response.status).to.eq(200)
const access_token = response.body.access_token
cy.log(access_token)
cy.log(this.access_token)
})
cy.log(this.access_token)
}),
it('Create Cart',function(){
cy.request({
method:'POST',
url: `${API_STAGING_URL}`+"/api/v1/cart",
headers:{
Authorization : 'Bearer ' + access_token,
"Content-Type": 'application/json',
"Cache-Control": 'no-cache',
"User-Agent": 'PostmanRuntime/7.29.2',
"Accept": '*/*',
"Accept-Encoding": 'gzip, deflate, br',
"Connection": 'keep-alive',
"Postman-Token": '<calculated when request is sent>'
},
}}).then((response)=>{
//Get statut 200
expect(response.status).to.eq(200)
//Get property headers
})})
})
This is a scoping issue - access_token does not exist outside of the block where it is created. Filip Hric has a great blog post on using variables with Cypress. My favorite strategy would be to store the value in a Cypress environment variable.
const API_STAGING_URL = Cypress.env('API_STAGING_URL');
describe('Decathlon API tests', () => {
it('Get token', function () {
cy.request({
method: 'POST',
url: 'https://test.com/as/token.oauth2?grant_type=client_credentials',
headers: {
authorization: 'Basic 1aFJueHkxddsvdvsdcd3cSA=='
}
}).then((response) => {
expect(response.status).to.eq(200);
Cypress.env('access_token', response.body.access_token);
cy.log(Cypress.env('access_token'));
});
});
it('Create Cart', function () {
cy.request({
method: 'POST',
url: `${API_STAGING_URL}` + '/api/v1/cart',
headers: {
Authorization: `Bearer ${Cypress.env('access_token')}`,
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'User-Agent': 'PostmanRuntime/7.29.2',
Accept: '*/*',
'Accept-Encoding': 'gzip, deflate, br',
Connection: 'keep-alive',
'Postman-Token': '<calculated when request is sent>'
}
}).then((response) => {
// Get statut 200
expect(response.status).to.eq(200);
// Get property headers
});
});
});
Another approach would be to create the access_token in a hook and then you can access it in a it() block.
There are a few ways to do it.
Using variable:
let text
beforeEach(() => {
cy.wrap(null).then(() => {
text = "Hello"
})
})
it("should have text 'Hello'", function() {
// can access text variable directly
cy.wrap(text).should('eq', 'Hello')
})
Using an alias:
beforeEach(() => {
cy.wrap(4).as("Number")
})
it("should log number", function() {
// can access alias with function() and this keyword
cy.wrap(this.Number).should('eq', 4)
})
Here is a working example.

LinkedIn API OAUTH returning "grant_type" error

I am pretty new to coding, but trying to write a simple script using LinkedIn's API that will pull an organizations follower count into google app script. Before I can even query the API, I have to authenticate using oath explained in the LinkedIn API here.
This function returns with an error response
function callLinkedAPI () {
var headers = {
"grant_type": "client_credentials",
"client_id": "78ciob33iuqepo",
"client_secret": "deCgAOhZaCrvweLs"
}
var url = `https://www.linkedin.com/oauth/v2/accessToken/`
var requestOptions = {
'method': "POST",
"headers": headers,
'contentType': 'application/x-www-form-urlencoded',
'muteHttpExceptions': true
};
var response = UrlFetchApp.fetch(url, requestOptions);
var json = response.getContentText();
var data = JSON.parse(json);
console.log(json)
}
When I try sending the headers through I get this error as a response
{"error":"invalid_request","error_description":"A required parameter \"grant_type\" is missing"}
grant_type, client_id, client_secret do not go in the header of the request. Instead, try to put them in the body of the POST request with the content type x-www-form-urlencoded as you already had in the headers of the code you posted.
For example:
fetch('https://www.linkedin.com/oauth/v2/accessToken/', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: '78ciob33iuqepo',
client_secret: 'deCgAOhZaCrvweLs'
})
})
.then(response => response.json())
.then(responseData => {
console.log(JSON.stringify(responseData))
})
Using Apps Script you should send the payload like so:
Example:
function callLinkedAPI() {
var payload = {
"grant_type": "client_credentials",
"client_id": "78ciob33iuqepo",
"client_secret": "deCgAOhZaCrvweLs"
}
var url = `https://www.linkedin.com/oauth/v2/accessToken/`
var requestOptions = {
'method': "POST",
'contentType': 'application/x-www-form-urlencoded',
'muteHttpExceptions': true,
"payload":payload
};
var response = UrlFetchApp.fetch(url, requestOptions);
var json = response.getContentText();
var data = JSON.parse(json);
console.log(json)
}

Posting to Bitly api with Google App Script returns 403

Hey Stackoverflow fellows!
I have been trying to writing an automation for my google sheets using an api from bit.ly to shorten my tons of link. Right now, I am at the fundamental stage and trying to log what the api return to me. Could you guys help an see what is wrong with the code? I am expecting the 200 returning back to me but it keep returning 403 forbidden to me.
var form =
{"long_url": "https://dev.bitly.com", "domain": "bit.ly", "group_guid": "MY GROUP ID" };
var option = {'header':'Authorization: Bearer{MY TOKEN}',
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(form)
};
var response = UrlFetchApp.fetch('https://api-ssl.bitly.com/v4/shorten', option);
Logger.log (response);
}
P.S. I tried to further expand the code by using adding title (succeeded) and customized link (short half // after bit.ly/ ). The second part keep return me 404. Or should I use Post/custom_bitlinks instead?
Here is my current code:
function bitlyori (i, title){
var form = {
"group_guid": "MINE",
"domain": "bit.ly",
"long_url": i,
"title" : title
};
const MY_TOKEN = "MINE";
const option = {
headers: { Authorization: `Bearer ${MY_TOKEN}` },
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(form),
};
var result = UrlFetchApp.fetch('https://api-ssl.bitly.com/v4/bitlinks', option);
return (JSON.parse(result.getContentText()));
}
function bitly(url,title,custom) {
var temp = bitlyori(url, title);
var form_2 = {
"custom_bitlinks": [temp] ,
};
const MY_TOKEN = "MINE";
const option_2 = {
headers: { Authorization: `Bearer ${MY_TOKEN}` },
method: 'patch',
payload: form_2};
var temp_link = 'https://api-ssl.bitly.com/v4/bitlinks/'+ JSON.stringify(temp)["id"];
var result_2 = UrlFetchApp.fetch(temp_link, option_2);
return (JSON.parse(result_2.getContentText()));
}
Headers should be a object with key "headers" inside options:
const MY_TOKEN = "dfjkgsa";
const option = {
headers: { Authorization: `Bearer ${MY_TOKEN}` },
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(form),
};
See:
Urlfetchapp ยง Advanced parameters

PUT request in Chrome Extension using Google API not rendering

I'm stuck at this point of my code wherein I have successfully called the Sheets API using PUT request, but it's not rendering on the Google Sheet.
Here is my code where I use both PUT and GET requests to see if the data changed:
background.js
chrome.identity.getAuthToken({ 'interactive': true }, getToken);
function getToken(token) {
console.log('this is the token: ', token);
var params = {
"range":"Sheet1!A1:B1",
"majorDimension": "ROWS",
"values": [
["Hi","Crush"]
],
}
let init = {
method: 'PUT',
async: true,
data: params,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
},
'contentType': 'json',
};
fetch(
"https://sheets.googleapis.com/v4/spreadsheets/1efS6aMlPFqHJJdG8tQw-BNlv9WbA21jQlufsgtMsUmw/values/Sheet1!A1:B1?valueInputOption=USER_ENTERED",
init)
.then((response) => console.log(response))
let request = {
method: 'GET',
async: true,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
},
'contentType': 'json',
};
fetch(
"https://sheets.googleapis.com/v4/spreadsheets/1efS6aMlPFqHJJdG8tQw-BNlv9WbA21jQlufsgtMsUmw/values/Sheet1!A1:B1",
request)
.then((response) => response.json())
.then(function(data) {
console.log(data)
});
}
Here's the screenshot of my Google Sheet, the data didn't change. The status of the PUT request is 200 and it seems the data is still Hello World in A1:B1:
Here's the log:
Do you have any idea what's missing here?
How about this modification? Please modify the object of init as follows.
From:
data: params,
To:
body: JSON.stringify(params),
Reference:
Using Fetch

Send json data to nodejs server

I have a problem sending json data to my node server
I tried
var req = {
method: 'POST',
url: 'http://33.33.33.15/user/signin',
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
},
data: {test:"test"}
};
when I console.log() req.body y have
{ '{"test":"test"}': '' }
When I try with
var req = {
method: 'POST',
url: 'http://33.33.33.15/user/signin',
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
},
data: 'test=test'
};
I have a good result on the server
I set the content type to application/x-www-form-urlencoded to allow the cross domain
On the server I have
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Thanks for the help
If you want to send it as JSON, then you may consider doing so:
var req = {
method: 'POST',
url: 'http://33.33.33.15/user/signin',
headers : {
'Content-Type' : 'application/json'
},
data: JSON.stringify({ test: 'test' })
};