Uncaught Reference Error: Jsonbody is not defined at Request.request - json

I am trying to show details of an api call in my electron app. this is the api and sample json data:
[
{
ID: 596,
title: "Carolyn Wood",
content: "<p>Turning away bad clients can leave you feeling oddly guilty. They’re sort of like alcoholic or meth head cousins who force you, by their own bad behavior into denying them things you wouldn’t deny other people. You’re left feeling not quite yourself. </p> ",
link: "https://quotesondesign.com/carolyn-wood/",
custom_meta: {
Source: "Twitter"
}
}
]
I am using request module to fetch data and JSON.parse(body) to get the object like below:
let request = require('request');
request("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback",
(err, response, body)=>{
let jsonBody = JSON.parse(body);
let randQuote = jsonBody[0]["content"];
document.getElementById("quote").innerHTML = randQuote;
});
In console, I get this error:
Uncaught ReferenceError: jsonBody is not defined
at Request.request [as _callback] (D:\ElectronDev\ElectronBasics\quote-widget\index.js:8
pointing on this line JSON.parse(body). How do I resolve this?

The response from the endpoint has some extra characters at the start of the response and that's the reason the JSON.parse can not parse it into object and jsonBody is undefined.
Here is the fix to your specific response for this. Change your line of code to this.
let jsonBody = JSON.parse(body.substring("/**/mycallback(".length, body.length - 1));
Hope this helps.

Related

FormatException (FormatException: Unexpected character (at character 1)

I am trying to get data from a json from a link and decode it to display data in a calendar, so it worked fine until this error appears in this line
dynamic jsonAppData = convert.jsonDecode(data.body);
Which trows this:
Exception has occurred. FormatException (FormatException: Unexpected
character (at character 1) <!doctype html><base href="https://accou... ^ )
I don't really know why it is caused, I searched for solutions but I didn't find anything for my case.
I hope you can help me.
Future<List> getDataFromGoogleSheet() async {
Response data = await http.get(
Uri.parse(
"https://script.google.com/macros/s/AKfycbybaFrTEBrxTIni8izFKMQYNNAe7ciVMlqF0OUHyWujjRR2AQ8zDyQzh96tleRKMHSN/exec"),
);
dynamic jsonAppData = convert.jsonDecode(data.body);
final List<Meeting> appointmentData = [];
for (dynamic data in jsonAppData) {
var recurrence = data['byday'];
Meeting meetingData = Meeting(
eventName: data['subject'],
from: _convertDateFromString(data['starttime']),
to: _convertDateFromString(data['endtime']),
background: Colors.grey.shade800,
recurrenceRule: 'FREQ=DAILY;INTERVAL=7;BYDAY:$recurrence;COUNT=10',
);
appointmentData.add(meetingData);
String notes = data['notes'];
}
return appointmentData; }
Your response body is not of json type.
You should check your request before
You can't parse the json because you have to authenticate with google first. If you call the page in the browser, where you are not logged in with Google, then you are redirected to the login page of Google. And my guess is this page is parsed, not the json.

Unexpected token S in JSON at position 0' Next auth

A teammate and I are working developing an application portal. We have the same exact code, node version and environment variables but when he logs in, he gets this error. I am able to login perfectly without any error. He was also able to login last week so at one point it was working for him.
A lot of solutions I've read about are adding code that trims or stringifies the JSON response. But it makes no sense that it works for me as it is but he would need to add code to make his work. Does anyone know why this is happening? (He has a NEXTAUTH_URL in the .env as well).
[next-auth][error][CLIENT_FETCH_ERROR]
https://next-auth.js.org/errors#client_fetch_error invalid json response body at http://localhost:3000/api/auth/session reason: Unexpected token S in JSON at position 0 {
error: {
message: 'invalid json response body at http://localhost:3000/api/auth/session reason: Unexpected token S in JSON at position 0',
stack: 'FetchError: invalid json response body at http://localhost:3000/api/auth/session reason: Unexpected token S in JSON at position 0\n'
I had the same error with next-redux-wrapper. I was implementing the old version's set up. I had this causing error:
export const getServerSideProps = wrapper.getServerSideProps(
async ({ req, params, store }) => {
const session = await getSession({ req });
if (!session) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}
await store.dispatch(getBookingDetails(req.headers.cookie, req, params.id));
}
);
I had to change it to:
// the way how I pass callback changed
export const getServerSideProps = wrapper.getServerSideProps(
(store) =>
async ({ req, params }) => {
....rest of the code
);
I recently encountered exactly the same problem but luckily managed to settle it.
The solution is to (1) NEXT_PUBLIC_SECRET is required in .env and (2) [...nextauth].ts added with secret: process.env.NEXT_PUBLIC_SECRET.
I have the following link to thank for the above solution.
Hope it works for you too.

API Response returns Mappable Object in iOS but Json on Android

I'm a newbie on mobile development and React-Native, this might come across as a very mundane thing to some of you, but I'm making an Api call and then mapping the results to create the same component but with different data.
This works fine on Iphone but on Android it does not.
The response from the req is an Object for both devices but on Android, it seems to be a json object that I simply cannot map with or use on a Flatlist.
I've tried JSON.parse to get the json object to a js object but it simply doesn't, like it. It throws out an unexpected token error.
I've attached a log for the Android object first and the same object for iPhone (Already mappable and a JS object).
Can someone tell me why this happens? I'd very much appreciate it!
enter image description here
____________________ After Changing to Fetch _______________________
Hey, I changed from Axios to fetch and now I get an unhandled promise warning saying 'Unhandled promise rejection: SyntaxError: JSON Parse error: Unrecognized token '' '.
Don't think I'm doing anything wrong here...
Well ... your response-object gets truncated due to memory issues on your real-device ... most likely your response object is kinda large ...
And that's just the way axios fetch response-data ... through chunks, you just get a slice of the response...
I came across this issue before ... and the solution was to switch to fetch
Edit
try {
const rawResponse = await fetch(...);
const text = await rawResponse.text();
console.log(text);
const parsedRes = JSON.parse(text);
console.log('parsedRes', parsedRes);
} catch(error) {
console.log('fetch error', error);
}

Decode http response in Angular - JSON.parse issue

After quite a bit of messing around, I've got to the point where I can recieve the following body in a 404 error response from my backend. I'm struggling to parse the content into angular so I can use it. I'm know this is simple stuff, so sorry to ask such a basic question. The _body looks like this.
_body: "{\"httpStatus\":404,\"errorType\":\"NotFound\",\"message\":\"Device does not exist!\"}"
These are fine:
console.log("Err = ", err);
Err = Response {_body: "
{\"httpStatus\":404,\"errorType\":\"NotFound\",\"message\":\"Device does not exist!\"}", status: 404, ok: false, statusText: "OK", headers: Headers, …}
and:
console.log("Err Body : ", err._body);
Err Body :
{\"httpStatus\":404,\"errorType\":\"NotFound\",\"message\":\"Device does not exist!\"}
But this doesn't work:
let errorObject = eval(errorString);
Uncaught (in promise): SyntaxError: Invalid or unexpected token
...
var errBody = JSON.parse(errorString);
console.log("JS err body", errBody);
Error: Uncaught (in promise): SyntaxError: Unexpected token \ in JSON at position 1
But I can't figure out how to get the individual fields out. I'm aware that the above efforts are naive and wrong. I'm sure anyone with JS or angular skills can solve this in a minute.
PS cut me some slack. I'm a hardware designer. I'm here because I don't know something, which is always the best reason to ask a question.
Edit:
Thanks for the answers. JSON.parse does not work for me!?
SyntaxError: Unexpected token \ in JSON at position 1
I looked more closely at what you had success with, and I agree it works fine in the console. But it does not work for me in Angular. What did work was:
let errBody = JSON.parse("\"" + err._body + "\"");
Although it seems ridiculous to do. Especially since, afterwards, the result is not quite right:
err body {"httpStatus":404,"errorType":"NotFound","message":"Device does not exist!"}
If I then try to get at errBody.message, it's undefined!... This is totally absurd. What am I doing wrong? How do you guys do this for a living? It's killing me!
I'm assuming errorString is err._body? Either way, parsing that string to JSON should be as simple as:
let error = JSON.parse(err._body);
I came back to this recently. And finally managed to figure it out. I needed to remove some unwanted backslashes in the body before trying JSON Parse.
const errorStringReplaced = err._body.replace(/\\/g, '');
const errBody = JSON.parse(errorStringReplaced);
this.outcomeMessage = errBody.message;
Having done that, I could then grab the innards properly. I'd still prefer to send the object properly in the first place, but this will have to do for now.

NodeJS request doesn't encode the entire form

The task is rather simple, I request the endpoint with POST request (https://banana.com/endpoint/swap.php), give it my form: { banana: ["China's Red", "Sweden's Gray"], apples: [] } and send it.
However, the Request module for NodeJS that I am using does not encode the empty array (in this case "apples") and if the endpoint doesn't receive the "apples" array, it returns an error - "Invalid JSON". I have tried doing this with already encoded strings and it works just fine. I am also unable to stringify my json and then use encodeURI(), as it will then give "bananas" and "apples" quotes around them, which will get encoded - needless to say, the endpoint doesn't like that either.
I'd really appreciate if somebody could at least point me in the right direction. As I am unsure on how to proceed with this, without creating some awful spaghetti code.
data = { banana: ["China's Red", "Sweden's Gray"], apples: [] }
result = JSON.parse(JSON.stringify(data)) .
You wouldn't get double around banana and apple and if you need to access then access it
console.log(result.banana)
console.log(result.apple)
So if you need to feed this result in post request then -
url = 'your url';
const options = {
url: url,
method: 'POST',
headers: {
Accept: 'application/json',
'Accept-Charset': 'utf-8'
},
json: result
};
request.post(options, function (err, response, body) {
// do something with your data
})
Let me know if this works.