PUT request in Chrome Extension using Google API not rendering - google-chrome

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

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.

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

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

Undefined data after responseJson is entered into state [] in ReactJS

I have a problem here, namely when I do the Post API and add console.log (responseJson) the data appears and its contents are (app_uid and app_number). But when I enter the API data into the dataApp [] state and I try console.log (this.state.dataApp), no data appears.
Here is a piece of script from its post API function:
onTask = (pro, tas) => {
fetch('https://bpm.***********.or.id/api/1.0/**********/cases/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Bearer ' + this.state.token,
},
body: JSON.stringify({
'pro_uid': pro,
'tas_uid': tas,
}),
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson); //here the data appears
this.setState({
dataApp: responseJson,
});
console.log(this.state.dataApp); //but here does not appear any data
});
Hopefully I can find a solution here, thank you very much.
this.setState is an asynchronous function.
Meaning - in your example, that you won't see its result on the next line where you console log it, because it is not yet done.
Try the following:
this.setState({
dataApp: responseJson,
}, () => console.log(this.state.dataApp)); // console.log inside a callback
To understand why it works inside a callback, and not in the next line, take a look at this MDN Article and this React Documentation
setState() is an async call in React. So you won't likely get the updated state value in the next line. You need to use the callback handler to get the updated value.
onTask = (pro, tas) => {
//Code you need to add
var that = this;
fetch('https://bpm.***********.or.id/api/1.0/**********/cases/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Bearer ' + this.state.token,
},
body: JSON.stringify({
'pro_uid': pro,
'tas_uid': tas,
}),
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson); //here the data appears
that.setState({
dataApp: responseJson,
}, () => {
console.log("dataApp: ", that.state.dataApp);
});
});

Bit.ly gives 404 from Google Apps Script

I am trying to shorten URLs from Google Apps Script, but I keep getting 404 errors and I don't know why. Please help.
function shortenUrl(longUrl){
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify({
"long_url": longUrl,
}),
// 'muteHttpExceptions': true,
'headers': {'Authorization': 'Bearer ' + BITLY_TOKEN,
// 'Host': 'https://api-ssl.bitly.com',
'Content-Type': 'application/json'}
};
return UrlFetchApp.fetch("https://api-ssl.bitly.com/v4/shorten HTTP/1.1", options).getContentText();
}
How about this modification?
Modified script:
function shortenUrl(longUrl){
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify({
"long_url": longUrl,
}),
// 'muteHttpExceptions': true,
'headers': {'Authorization': 'Bearer ' + BITLY_TOKEN} // Modified
};
return UrlFetchApp.fetch("https://api-ssl.bitly.com/v4/shorten", options).getContentText(); // Modified
}
For above script, please confirm whether BITLY_TOKEN is declared, again.
References:
Class UrlFetchApp
Bitly API (4.0.0)

Request parameters in a post request in parse.com

For a service called mOTP, I need to send a parameter with name 'private'. Here is my Parse cloud code.
var phnNum = request.params.phnNum;
var validationParams = {"private":"MyPrivateKey"};
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://api.mOTP.in/v1/otp/MyAPIKey/'+MySessionID,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
params: validationParams,
success: function(httpResponse) {
console.log(httpResponse.data.Status);
console.log(httpResponse.data.Result);
if(phnNum == httpResponse.data.Result) {
response.success("Success");
} else {
response.error("phnNum not matched");
}
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error("URL hit failed");
}
});
The mOTP service gives response in JSON. But always I am getting the response as 'Method not supported'. I am not able to find where I am doing mistake. Please help.
mOTP docs: http://dial2verify.com/mOTP_Missed_Call_OTP_Authentication/Documentation.html
First of all, You should pass a body message with the POST method.
The content-type should be 'application/x-www-form-urlencoded' according to the documentation.
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://motp.p.mashape.com/v1/otp/{APIKey}/{SessionId}',
headers: {
'X-Mashape-Key': 'YOUR-X-Mashape-Key',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: {'private': 'Your_mOTP_Private_Key'},
success: function(httpResponse) {
response.success(httpResponse.text);
},
error: function(httpResponse) {
response.error("error: " + httpResponse.status);
}
});