I know this is common question, but I keep getting this error when fetching data:
SyntaxError: Unexpected token u in JSON at position 1 at JSON.parse ()
This happened when I testing my full code, so I made tested with
res.send(JSON.stringify({"data": "test"}));
In my client side, I'm using this code:
fetch(url) // fetch works
.then(checkStatus) // checks for errors, if none send response text
.then(function (responseText) {
let data = JSON.parse(responseText); // where I'm getting the error
When testing the values, everything in my server side prints the correct values. However, when I use console.log to print out the responseText on the client side, I get this:
f text() { [native code] }
Why is this error being called? From looking around stack overflow, I understand that this error happens when I attempt to parse a string that's undefined. I put an if statement before the parse to check is the string is undefined:
if (responseText === undefined) {
console.log("responseText is undefined");
}
But it didn't output, so is the string really undefined? As a side note, node is up to date. Thank you for helping.If this is answered in another question, please let me know. I haven't found a solution to this problem.
Edit:
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response.text;
} else if (response.status === 404) {
clear();
return Promise.reject(new Error("Sorry, we couldn't find that page"));
} else {
console.log(response.text());
return Promise.reject(new Error(response.status + ": " + response.statusText));
}
}
Edit: response.text is supposed to be response.text(). This gave me my error.
A promise chain resolves each new promise with the return value from the last.
You should note the fetch()
API returns a Promise
resolving with a Response
object. This does not have a text
property, so checkStatus
is resolving with undefined
(hence the "u" in the error message).
I suggest you use the Body.json()
method to parse the JSON response, ie change checkStatus
to use
if (res.ok) { // same as checking status between [200, 300)
return res.json()
}
if (res.status === 404) {
clear()
return Promise.reject(new Error("Sorry, we couldn't find that page"))
}
// text(), like json() returns a promise
return res.text().then(responseText => {
console.error(responseText)
return Promise.reject(new Error(`${res.status}: ${res.statusText}`))
})
and for fetch()
...
fetch(url)
.then(checkStatus)
.then(data => {
// data is already parsed into an object
})
On the server-side, you might want to use res.json()
instead of manually stringifying your data
res.json({ data: 'test' })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With