Fetch API SyntaxError: Unexpected token { in JSON at position 169681 - javascript

Im trying to make an HTTP request using fetch, but it's blowing up with the error: "SyntaxError: Unexpected token { in JSON at position 169681". This is my request function:
async getOportunidades() {
try {
const response = await fetch('https://gcsupport.internal.vodafone.com/bpa/webservices/GCCRM.asmx/GetCardsLeadsList',
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify({userId: 29188,tipoAplic:'T'})
});
const data = await response.json();
this.listaOportunidades = data;
return data
} catch(e) {
console.log(e);
}
}
Looking at the response at Chrome developer tools all seems fine:
and after inspecting it seems I am receiving my json data as expected, and the json string is well formed, but for some reason it "breaks" on position 169681.
Is there like a size limit on the response?!
Just for the sake of my sanity I tried to make the same request using Jquery AJAX and everything runs fine!! Thing is, I don't want to use Jquery on my project. Anyone more experienced with Fetch has any idea why this is happening?
*********MY AJAX CALL********
$.ajax({
url:'https://gcsupport.internal.vodafone.com/bpa/webservices/GCCRM.asmx/GetCardsLeadsList',
type: 'POST',
data: {userId: 29188, tipoAplic: 'T'},
success: function(data) {
console.log(data)
},
error: function(xhr, status, error) {
console.log(xhr, status, error)
}
})
******webservice code*******
Sorry if this is a duplicate question but all the issues I could find were related to "Unexpected token < at position 0" which is not my case.
Thanks in advance
Cheers

Your web service is not handling JSON requests correctly. I've created a fetch example below that uses form data that should work. $.ajax interprets the object given as form data which is why it works.
What's happening is that your web service outputs BOTH data generated from JSON body and form data. It needs to be fixed to immediately return after handling JSON body, and not continuing to try to interpret form data (which in the case of a JSON body is blank).
tl;dr Web service is bugged. Does not end writing response after using JSON body data to generate response. So, after .write(responseFromJSONData()) it doesn't return and break, and tries to continue to .write(responseFromFormData([blankFormData])), resulting in two JSON objects being attached to your response.
async getOportunidades() {
try {
const response = await fetch('https://gcsupport.internal.vodafone.com/bpa/webservices/GCCRM.asmx/GetCardsLeadsList',
{
headers: {
'Accept': '*/*',
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
method: 'POST',
body: new URLSearchParams({userId: 29188,tipoAplic:'T'})
});
const data = await response.json();
this.listaOportunidades = data;
return data
} catch(e) {
console.log(e);
}
}

var data = JSON.stringify({"userId":29188,"tipoAplic":"T"});
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://gcsupport.internal.vodafone.com/bpa/webservices/GCCRM.asmx/GetCardsLeadsList");
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(data);
Try this one.

Related

How to send a webhook using Office Script?

I need to connect Excel to Zapier through a webhook but can't make it work so far. I manage to send a webhook using this code but don't receive any data in the body.
function sendMessage() {
var request = new XMLHttpRequest();
request.open("POST", "https://hooks.zapier.com/hooks/catch/2251620/bv6gjw6/");
request.setRequestHeader('Content-type', 'application/json');
var content = { "value1": "test data" };
request.send(JSON.stringify(content));
}
sendMessage()
}```
Tried every code snippet out there but couldn't make it work. Pasted JSON data as well.
I've found the culprit - mode: 'no-cors'needs to be added. Here's the end result, you can send webhooks from Excel Script with that:
async function main(workbook: ExcelScript.Workbook) {
async function sendWebhook(data:string) {
let response = await fetch('https://hooks.zapier.com/hooks/catch/2251620/bv6gjw6/', {
method: 'POST',
mode: 'no-cors',
headers: { 'Content-Type': 'application/json' },
body: data,
});
return response;
//const json = await response.json();
//return json;
}
let data = JSON.stringify({ message: 'Hello, Excel!' });
let response= await sendWebhook(data);

How should i format my JSON in Vue using Axios to look like this?

I've spent hours trying to figure out how to format my JSON in Vue.js to send it this way:
At the moment I'm trying to do it with a FormData() object, but the result is still just:
My function looks like this:
register () {
var bodyFormData = new FormData();
bodyFormData.append('firstname', 'Coca');
bodyFormData.append('lastname', 'Cola')
console.log(jsonData)
axios({
method: 'post',
url: 'backend/index.php?action=createUser',
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
}
I've achieved the result on the first picture through jQuery AJAX calls, is this also possible with Axios in Vue?
You can use the JSON.stringify method and append your object to your form data.
bodyFormData.append('data', JSON.stringify(jsonData));
You are explicitly using Content-Type: multipart/form-data and sending form data for your data parameter. To send JSON, set data to the object you want to serialize as JSON, and use application/json as your content-type.
async register () {
try {
const response = await axios({
method: 'post',
url: 'backend/index.php?action=createUser',
data: { firstname: 'Coca', lastname: 'Cola' },
headers: {'Content-Type': 'application/json' }
});
//handle success
console.log(response);
} catch (err) {
//handle error
console.log(err);
}
}
Thanks for your answers, I actually had to make a FormData and populate it with stringified JSON data.

Calling a Rest API from tfs extension with JScript

I am basicly using 3 diffrent JS methods to get the data from the api but they return the error 405: Method Not Allowed but server has the get method in it as allowed. It is using path for the variable so I am wondering if it is related to that.
Here are the Codes for Methods that i call the API.
Fetch Method;
function getCompleted(queryParam) {
$('#loader').removeClass('hidden');
$('#loaded').addClass('hidden');
fetch("****/fullprofile/" + queryParam, {
method: "GET", headers: {
"User": "*****",
"Content-Type": "application/json"
}
})
.then((data) => {
const contentType = response.headers.get('content-type');
console.log(contentType);
return data.json()
})
.then(function (result) {
ResponseBody = result;
$('#loader').addClass('hidden');
$('#loaded').removeClass('hidden');
}).catch(function () {
$('#loader').addClass('hidden');
$('#loaded').removeClass('hidden');
});
}
HTTP Request Method;
function httprequest(queryParam2) {
$('#loader').removeClass('hidden');
$('#loaded').addClass('hidden');
var xmlhttp = new XMLHttpRequest();
xmlhttp.withCredentials=true;
var url = "*****/fullprofile/";
xmlhttp.onreadystatechange = function (data) {
console.log(this.responseText);
console.log(data);
}
xmlhttp.open("GET", url + queryParam2);
xmlhttp.setRequestHeader("User", "*****");
xmlhttp.send();
}
Ajax Method;
function ajax(queryParam3) {
$.ajax({
url: "****/fullprofile/" + queryParam3,
"method":"GET",
"headers":{
"User":"EBT\\****"
},
success: function (data) {
ResponseBody = data;
console.log(data);
}
});
}
Thank you all for the advices and help.
the reason was sending with headers; it returns options that needs to be responded again and it wasn't worth doing in JS so i decided to make a gateway api to use the api i have with header.
Thank you.
It is possible that the resource you are trying to consult does not use the verb GET.
you have to confirm with which verb the resource is obtained
Look here:
405 Method Not Allowed MDN Docs
Confirm in the documentation of the api with which verb that resource is requested. I could be POST, PUT etc
Here you can look explanation

javascript fetch() works with breakpoints, but fails with TypeError when run normally

I'm trying to fetch() text/plain data from a remote service. If I place a breakpoint in the promise "then" chain, the text data from the server is available. Without the breakpoint, I get a fetch() exception.
I am using a prototype design pattern (see below). When I place a breakpoint in the "then" chain as shown below, the data from the remote service is successfully retrieved. Without the breakpoint, the catch() is executed and the error is:
TypeError: Failed to fetch
I'm totally stumped and would appreciate any help!
Note, the server (a python app) sends back html, with
self.send_header("Access-Control-Allow-Origin", "*")
Also, if I use Ajax (FWIW, it works). I'd like to get it working with fetch() however.
function Fetch(Msg) {
// Msg contains some info on how to construct the JSON message to transmit -- not relevant here.
this.help = `
The Fetch object specifies communication basics using
the fetch(...) mechanism.
`;
// some misc object vars...
}
Fetch.prototype = {
constructor: Fetch,
postData: async function (url = '', data = {}) {
const response = await fetch(url, {
method: 'POST,
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'text/plain',
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
// body data type must match "Content-Type" header
body: JSON.stringify(data)
});
return await response.text(); //
},
handleErrorsInResponse: function (response) {
var debug = new Debug("Fetch.handleErrorsInResponse");
debug.entering();
debug.leaving();
},
handleReponse: function (response) {
var debug = new Debug("Fetch.handleResponse");
debug.entering();
console.log(response);
debug.leaving();
},
handleErrorsInFetch: function (response) {
var debug = new Debug("Fetch.handleErrorsInFetch");
debug.entering();
console.log(response);
debug.leaving();
},
call: function (payload) {
this.postData(
'http://some.url/',
payload)
.then(this.handleErrorsInResponse) // If I place a breakpoint here it works!
.then(this.handleReponse)
.catch(this.handleErrorsInFetch);
},
}
// Ultimately called by something like
comms = new Fetch();
someData = {"key": someJSON};
comms.call(someData);
Remove the wait on the response.
Replace
return await response.text();
by
return response.text();

How to call a function only after getting response from restcall node js

I have one request.post call and another function.Where I need to pass the response of restcall as paramaters to the function.
The current issue which Iam facing here is that the function is getting called even before i get response from the rest call and null values are getting passed.I know that we need to use some callabcks for this issue.But I dont know how to do it.can someone help.
app.post('/verifycreds',function(req,res) {
var reqdata = req.body;
var data = {};
data.custid = reqdata.custid;
request.post({
url:'https://database.mybluemix.net/verifycredentials',
headers:{
'Content-Type':'application/json'
},
body:data,
json:true
}, function(err,response) {
verifycreds(response.body);
});
function verifycreds(data) {
if((datareq.customerid === data.customerid ) && (datareq.password == data.password)){
res.send("valid");
} else {
res.send("invalid");
}
}
So how can I call verifycreds function only after I get response from the request .post call..Any help!
Your callback is valid, the problem in callback parameters. It should be defined with three parameters:
error
response
body
So correct code is:
request.post({
url: 'https://database.mybluemix.net/verifycredentials',
headers: {
'Content-Type': 'application/json'
},
body: data,
json: true
}, function(err, res, body) {
// TODO: process possible errors
// if (err) { ...
verifycreds(body);
});

Categories

Resources