Node 'request' package, get string instead of object - json

let url = 'https://www.example.com';
let requestData = {
"key": {
"keyA": "value",
}
};
let options = {
url: url,
method: "POST",
headers: {
"Content-Type": "application/json",
},
json: requestData
};
request(options, function(err,httpResponse,result){});
How could I get the result as string instead of object?

Related

Google Apps Script call Address Validation API

Simple code and straightforward. It works with postman but fails with Apps Script.
function validateAddress () {
const url = 'https://addressvalidation.googleapis.com/v1:validateAddress?key=';
const apikey = '...';
let payload, options, temp;
payload = JSON.stringify({
"address": {
"addressLines": "1600 Amphitheatre Pkwy"
}
});
options = {
'muteHttpExceptions': true,
'method': 'POST',
'Content-Type': 'application/json',
'body': payload
}
temp = UrlFetchApp.fetch(url + apikey, options);
Logger.log(temp)
}
Error:
{
"error": {
"code": 400,
"message": "Address is missing from request.",
"status": "INVALID_ARGUMENT"
}
}
EDIT:
Change options to
options = {
'muteHttpExceptions': true,
'method': 'POST',
'Content-Type': 'application/json',
'payload': payload
}
Gives error:
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"{\"address\":{\"addressLines\":\"1600 Amphitheatre Pkwy\"}}\": Cannot bind query parameter. Field '{\"address\":{\"addressLines\":\"1600 Amphitheatre Pkwy\"}}' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"{\"address\":{\"addressLines\":\"1600 Amphitheatre Pkwy\"}}\": Cannot bind query parameter. Field '{\"address\":{\"addressLines\":\"1600 Amphitheatre Pkwy\"}}' could not be found in request message."
}
]
}
]
}
}
Documentation:
https://developers.google.com/maps/documentation/address-validation/requests-validate-address
From the documentation, it seems that addressLines is an array of string, not a string. Does that change something ? (I don't have a key, so I cannot try myself).
And more important, your options object is incorrect (check doc). It should be
options = {
'muteHttpExceptions': true,
'method': 'POST',
'contentType': 'application/json',
'payload': payload
}
I don't know why it works but changed options to
options = {
'muteHttpExceptions': true,
'method': 'POST',
'headers': {
'Content-Type': 'application/json'
},
'payload': payload
}
Solves the problem.

SyntaxError: Unexpected token \n in JSON at position

I have a roblem while directing a request from Cloud Flare workers to my API. When I catch the error I get this:
SyntaxError: Unexpected token \n in JSON at position 240
when I did some research I saw some articles about it being about JSON.parse. But I couldn't find the solution.
Example Request Body:
{"link": "link", "provider": "company", "oauth": "key", "testText": "text"}
Cloud Flare Workers Code:
addEventListener('fetch', function (event) {
const { request } = event;
const response = handleRequest(request).catch(handleError)
event.respondWith(response)
})
async function handleRequest(request) {
const realBody = JSON.parse(`${await request.json()}`
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r")
.replace(/\t/g, "\\t")
.replace(/\f/g, "\\f"));
const stringifiedJSON = JSON.stringify(realBody);
const init = {
body: stringifiedJSON,
method: "POST",
headers: {
"content-type": "application/json;charset=UTF-8",
},
};
const initLog = {
body: JSON.stringify({ msg: { discountBodyStringified: realBody }}),
method: "POST",
headers: {
"content-type": "application/json;charset=UTF-8",
},
}
const responseLogger = await fetch("https://example.com/log", initLog)
console.log(responseLogger)
console.log(init)
const response = await fetch("https://example.com", init)
return new Response("tweet sent!")
}
function handleError(error) {
console.error('Uncaught error:', error)
const { stack } = error
const initLog = {
body: JSON.stringify({ msg: { error: stack || error }}),
method: "POST",
headers: {
"content-type": "application/json;charset=UTF-8",
},
}
const responseLogger = fetch("https://example.com/log", initLog)
return new Response(stack || error, {
status: 500,
headers: {
'Content-Type': 'text/plain;charset=UTF-8'
}
})
}
problem is not in the code, the problem in request which you are or front app is sending somewhere you lived extra comma or didnt close field.
For example:
{
"name": "Alice",
}
this will give same error as SyntaxError: Unexpected token \n in JSON at position because extra comma is there or
{
"name": "Alice
}
this also will throw error because I didnt close quotes

How to create post using Google My Business API - Google Apps Script

I can't figure out why I'm getting the below error when I attempt to create a post with the GMB API in Google Apps Script. I'm following this documentation https://developers.google.com/my-business/content/posts-data
{
"error": {
"code": 400,
"message": "Request contains an invalid argument.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.mybusiness.v4.ValidationError",
"errorDetails": [
{
"code": 2,
"field": "summary",
"message": "Standard local post must have at least a media or summary."
}
]
}
]
}
}
Here is my script
function callToActionPost() {
var url = 'https://mybusiness.googleapis.com/v4/accounts/123/locations/456/localPosts';
var options = {
headers: { Authorization: "Bearer " + getGMBService_().getAccessToken() },
method: 'POST',
muteHttpExceptions: true,
languageCode: "en",
topicType: "STANDARD",
summary: "New Release!",
callToAction: {
actionType: "ORDER",
url: "https://www.artivem.com/"
},
media: {
sourceUrl: "https://untappd.akamaized.net/photos/2021_04_16/ccff4c358e362ce3c4835fcc94549a8f_640x640.jpg",
mediaFormat: "PHOTO"
}
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
I tried the following adaption, but it did not work
function callToActionPost() {
var url = 'https://mybusiness.googleapis.com/v4/accounts/123/locations/456/localPosts';
var options = {
headers: { Authorization: "Bearer " + getGMBService_().getAccessToken() },
method: 'POST',
muteHttpExceptions: true,
payload: {
languageCode: "en",
topicType: "STANDARD",
summary: "New Release!",
callToAction: {
actionType: "ORDER",
url: "https://www.artivem.com/"
},
media: {
sourceUrl: "https://untappd.akamaized.net/photos/2021_04_16/ccff4c358e362ce3c4835fcc94549a8f_640x640.jpg",
mediaFormat: "PHOTO"
}
}
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
Thanks in advance!
The request object needs to go into the payload. "payload" is a parameter of the options.
function callToActionPost() {
var url = 'https://mybusiness.googleapis.com/v4/accounts/123/locations/456/localPosts';
var payload = {
"languageCode": "en-US",
"summary": "New Release!",
"callToAction": {
"actionType": "ORDER",
"url": "https://www.artivem.com/"
},
"media": [{
"sourceUrl": "https://untappd.akamaized.net/photos/2021_04_16/9999999999999999.jpg",
"mediaFormat": "PHOTO"
}]
}
var options = {
headers: { Authorization: "Bearer " + getGMBService_().getAccessToken() },
method: 'POST',
muteHttpExceptions: true,
'contentType': 'application/json',
'payload' : JSON.stringify(payload)
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
if (response.getResponseCode() !== 200) {
console.log("Error Code: " + response.getResponseCode());
}
}

Condition based API url in JSON

I am using a JSON to make a call to some APIs. My sample JSON is something like :
{
"call": [
{
"url": "https://URL",
"httpMethod": "POST",
"httpHeaders": {
"Accept": "application/json",
"Content-Type": "application/json"
},
"httpContentType": "application/json"
}
]
}
My requirement is to select the URL based on some condition. For example, if employeeType='Employee'
the url in the above JSON should be https://URL1 and if employeeType='Contractor' then the url should be https://URL2.
Is this possible to achieve? and how?
Yes possible. You can use JsonConvert.SerializeObject and write to the file.
Here is the code.
dynamic json = JsonConvert.DeserializeObject<object>(jsson);
int count = 0;
foreach (dynamic item in json["call"])
{
if (item.employeeType=="Contractor")
{
json["call"][count].url = "https://URL2";
string output = JsonConvert.SerializeObject(json, Formatting.Indented);
File.WriteAllText("YOUR JSON DATA PATH", output);
count++;
}
else if (item.employeeType == "Employee")
{
json["call"][count].url = "https://URL1";
string output = JsonConvert.SerializeObject(json, Formatting.Indented);
File.WriteAllText("YOUR JSON DATA PATH", output);
count++;
}
}
And here is the json file that I edited.
{
"call": [
{
"url": "https://URL2",
"httpMethod": "POST",
"httpHeaders": {
"Accept": "application/json",
"Content-Type": "application/json"
},
"httpContentType": "application/json",
"employeeType": "Contractor"//I added employeeType if you want to fetch data from here
},
{
"url": "https://URL1",
"httpMethod": "POST",
"httpHeaders": {
"Accept": "application/json",
"Content-Type": "application/json"
},
"httpContentType": "application/json",
"employeeType": "Employee"
},
{
"url": "https://URL1",
"httpMethod": "POST",
"httpHeaders": {
"Accept": "application/json",
"Content-Type": "application/json"
},
"httpContentType": "application/json",
"employeeType": "Employee"
}
]
}

UrlFetchApp Post Variables Not being sent/received by php server

var headers = {
"Accept": "application/json",
"Content-Type": "application/json"
};
var data = {
action: "test123"
};
var options = { "method":"POST",
"headers" : headers,
"followRedirects": false,
"validateHttpsCertificates": false,
"muteHttpExceptions" : true,
"contentType": "application/json",
"payload": JSON.stringify(data)
};
var requestURL = "http://requesturl.com/controller.php";
var response = UrlFetchApp.fetch(requestURL, options);
Logger.log(response.getContentText());
on the php server in controller.php
<?php
echo ($_POST['action']);
?>
I get nothing for the echo but I do get a 200 response code, any help would be much appreciated!!!!!!!!!
What result do you get trying the code:
var data = {
'action': 'test123'
};
var options = { "method":"POST",
"headers" : headers,
"followRedirects": false,
"validateHttpsCertificates": false,
"muteHttpExceptions" : true,
"contentType": "application/json",
"payload": data
};