SyntaxError: Unexpected token \n in JSON at position - json

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

Related

How do i make a POST request to an api in React Native?

I am trying to make a Post request to an api but for some reason i am getting a 400 feedback in the process. Being that i am a beginner at this, i can't really figure out where i am getting it wrong. I understand 400 error has to do with incorrect syntax but i am not sure that is the case here. I also checked out the other related posts but none helped address my problem. I have also read through the documentation over and over again but still can't see where i am making a mistake. I will appreciate if you helped me point out the problem.
myPostRequest(){
var mybody = {
"amount": "5.0",
"currency": "EUR",
"externalId": "6547864",
"payer": { "partyIdType": "MSISDN","partyId": "0977948551"}
}
mybody = JSON.stringify(mybody);
var token = "mytoken";
//POST request
fetch('https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay', {
method: "POST",
headers: {
'Authorization': 'Bearer '+token,
'X-Reference-Id': 'f9b8b0a-XXXXXXXXXX',
'X-Target-Environment': 'sandbox',
'Ocp-Apim-Subscription-Key': '14d2a71dXXXXXXXXX',
},
body: mybody,
})
.then((responseJson) => {
alert(JSON.stringify(responseJson));
console.log(responseJson);
})
.catch((error) => {
alert(JSON.stringify(error));
console.error(error);
});
}
Use axios/apisauce instead of fetch
apisauce example:
import { create } from 'apisauce';
const api = create({
baseURL: `http://example.com`,
});
const response = await api.post('/path/to/', body, { headers });
In your case:
import { create } from 'apisauce';
const api = create({
baseURL: `https://sandbox.momodeveloper.mtn.com`,
});
const response = await api.post(
'/collection/v1_0/requesttopay',
{
"amount": "5.0",
"currency": "EUR",
"externalId": "6547864",
"payer": { "partyIdType": "MSISDN", "partyId": "0977948551" }
},
{
headers: {
'Authorization': 'Bearer ' + token,
'X-Reference-Id': 'f9b8b0a-XXXXXXXXXX',
'X-Target-Environment': 'sandbox',
'Ocp-Apim-Subscription-Key': '14d2a71dXXXXXXXXX',
}
}
);

react native, json response from POST. JSON unexpected EOF

If I do this in PostMan, I get a response back which I can toggle html and json, but in my react native app I'm getting a console error of JSON Parse Error: Unexpected EOF
I have the content type of my sent header as x-www-form-urlencoded because that was the only way to get my proper response even on postman.
I have my backend in wordpress sending a response array as json_encoded (echo json_encode($response)) and I can get it by url and post man, but my app just can't get past this unexpected EOF and I think it has to do with my .then statements
WHat am I doing wrong here?
validate(){
const {navigate} = this.props.navigation;
this.setState({ validating: true });
let formData = new FormData();
formData.append('type', 'login');
formData.append('email', this.state.email);
formData.append('password', this.state.password);
return fetch('https:/site/authentication.php', {
method: 'POST',
body: JSON.stringify(formData),
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => response.json())
.then(data => {
console.log(data);
return data;
})
.catch(function(err) {
console.log(err);
})
}
Looking at your response:
Response { "_bodyBlob": Blob { "_data": Object { "blobId": "31418cda-5d2e-4ee0-8c67-626e7ebe0502", "offset": 0, "size": 0, }, }, "headers": Headers { "map": Object { "cache-control": "public, max-age=0", "content-length": "0", "content-type": "text/html; charset=UTF-8", }, }, "ok": true, "status": 200, "statusText": undefined, "type": "default", "url": "https://site/authentication.php", } Promise { "_40": 0, "_55": null, "_65": 0, "_72": null, }
I think it is a blob not JSON. Try and use this instead:
.then(response => response.blob())
Sorry I missed that earlier.
Blob MDN Ref: response.blob()

Node 'request' package, get string instead of object

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?

Error:In JSON data submission unexpected character

I am trying to send a push notification using onesignal.In that process i got an error
"error":"There was a problem in the JSON you submitted: unexpected character at line 1, column 1 [parse.c:652]"}
My Code is as follows:
var jsonBody = {
"app_id": "OneSignal App ID",
"include_player_ids": ["Onesignal Playerid"],
"headings": {
"en": "Sump"
},
"contents": {
"en": " Sump Level is 'Sumpper' "
}
};
var request = $.ajax({
url: "https://onesignal.com/api/v1/notifications",
headers: {
'Authorization':'Basic REST API Key',
'Content-Type':'application/json',
'Access-Control-Allow-Headers': 'SDK-Version',
'Access-Control-Allow-Origin': '*'
},
type: "POST",
data: jsonBody,
dataType: "json"
});
console.log(request);
request.success(function(msg) {
console.log("success");
});
request.error(function(jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
Can anyone help me where i am going wrong.
Thankyou.
Hi try to create an object then stringfy it to json.
var jsonBody =
{
app_id: "OneSignal App ID",
include_player_ids: [ "Onesignal Playerid", "Secondsignal Playerid"],
headings :
{
en: "Sump"
},
contents :{
en: "Sump Level is 'Sumpper' "
}
};
var request = $.ajax({
url: "https://onesignal.com/api/v1/notifications",
headers: {
'Authorization':'Basic REST API Key',
'Content-Type':'application/json',
'Access-Control-Allow-Headers': 'SDK-Version',
'Access-Control-Allow-Origin': '*'
},
type: "POST",
data: JSON.stringify(jsonBody),
dataType: "json"
});
console.log(request);
request.success(function(msg) {
console.log("success");
});
request.error(function(jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});

Node Getting JSON_PARSING_ERROR

I am trying to call GCM notification by using POST.
The code I am using is :
var jsonbody={"to": "/topics/global",
"data": {
"title": "TestTitle",
"is_background": false,
"message": "Testmessage",
"image": "",
"payload": {
"team": "India",
"score": "5.6" },
"timestamp": "2016-12-13 16:32:05"
}
};
var request = require('request');
request.post({
headers: {'content-type': 'application/json',
Authorization:'key=(my key)'},
url: 'https://fcm.googleapis.com/fcm/send',
BODY: jsonbody
}, function (error, response, body) {
if (error) {
console.log('failure ' + error);
} else {
console.log('success '+response + 'and ' +body);
}
});
I am getting error as :
success [object Object]and JSON_PARSING_ERROR: Unexpected token END
OF FILE at position 0.
I was actually missing something :
body: JSON.stringify(jsonbody)
Rest all was correct.