SyntaxError: Unexpected token in JSON at position 0
The wording of the error message corresponds to what you get from Google Chrome when you run JSON.parse('<...')
. I know you said the server is setting Content-Type:application/json
, but I am led to believe the response body is actually HTML.
Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0"
with the line
console.error(this.props.url, status, err.toString())
underlined.
The err
was actually thrown within jQuery
, and passed to you as a variable err
. The reason that line is underlined is simply because that is where you are logging it.
I would suggest that you add to your logging. Looking at the actual xhr
(XMLHttpRequest) properties to learn more about the response. Try adding console.warn(xhr.responseText)
and you will most likely see the HTML that is being received.
What is Unexpected token a in JSON at position 0?
Unexpected Token < in JSON at Position 0. From time to time when working with JSON data, you might stumble into errors regarding JSON formatting. For instance, if you try to parse a malformed JSON with the JSON. ... json() method on the fetch object, it can result in a JavaScript exception being thrown.
What Is JSON and How to Handle an “Unexpected Token” Error
fetch returns SyntaxError: Unexpected token T in JSON at position 0
This type of error usually happens when your server returns something which is not JSON. In my experience, 99% of the time the server is returning a generic error message. Often times servers will have a generic "catch all" error handler which returns something like:
There was an error processing your request.
In this case, if you tried to use JSON.parse
(or res.json()
in your case), you would get the error you are experiencing. To see this, paste this into your console:
JSON.parse("There was an error processing your request.")
//-> Uncaught SyntaxError: Unexpected token T in JSON at position 0
Solution 1: Usually the server will set a proper status code whenever there is an error. Check to make sure the response status is 200 before parsing:
fetch('...').then(res => {
if (res.status !== 200) {
throw new Error(`There was an error with status code ${res.status}`)
}
return res.json()
)
Solution 2: Update your server code to return an error message in JSON format. If you're using node and express, this would look something like this:
function errorHandler (err, req, res, next) {
if (res.headersSent) return next(err)
const message = 'There was an error processing your request.'
res.status(500)
if (req.accepts('json')) {
// The request contains the "Accept" header with the value "application/json"
res.send({ error: message });
return;
}
res.send(message);
}
Then, you would update your frontend code accordingly:
fetch('...')
.then(res => res.json())
.then(res => {
if (res.error) {
throw new Error(res.error)
}
return res
)
JSON.parse(): SyntaxError: Unexpected token � in JSON at position 0
Your JSON file seems to have a different encoding, maybe is utf16le instead of utf8.
I replicated your scenario and found help here:
Strange unicode characters when reading in file in node.js app
fs.readFile(file, 'utf16le', (err, data)...
Django : Uncaught (in promise) SyntaxError: Unexpected token in JSON at position 0
JavaScript
<script>
var id_order = document.getElementsByClassName('id_order')
for (i = 0; i < id_order.length; i++) {
id_order[i].addEventListener('click', function(){
var orid = this.dataset.product
var ornm = this.dataset.act
console.log('orid :', orid)
console.log('ornm :', ornm)
data(orid, ornm)
})
}
function data(orid, ornm){
console.log('orid :', orid, 'ornm :', ornm)
const url = "Detail"
fetch(url, {
method :'POST',
headers : {
'Content-Type' : 'application/json',
'X-CSRFToken' : csrftoken,
},
body:JSON.stringify({'orid':orid, 'ornm':ornm}),
})
.then((response) => response.json())
.then((data) => {
console.log('Success:', data);
window.location.href = "{% url 'Detail_pem' %}"
})
}
</script>
view.py
def Detail_pem(request):
data = json.loads(request.body.decode("utf-8"))
orid = data['orid']
ornm = data['ornm']
print('id :', orid, 'nama :', ornm)
context = {'orid ':orid , 'ornm':ornm}
return render(request, 'store/detail.html', context )
def Detail(request):
data = json.loads(request.body.decode("utf-8"))
orid = data['orid']
ornm = data['ornm']
print('id :', orid,'nama :', ornm)
return JsonResponse('Payment complete', safe=False)
Getting Error like that
JSONDecodeError at /Detail_pem
Expecting value: line 1 column 1 (char 0)
enter image description here
Related Topics
No Visible Cause For "Unexpected Token Illegal"
Ecmascript Template Literals Like 'Some ${String}' Are Not Working
How to Highlight Text Using JavaScript
Converting an Object to a String
Check Browser CSS Property Support with JavaScript
Can Jquery Change CSS Style Definition? (Not Individual CSS of Each Element)
Setting Rounded Corners for Svg:Image
Call Java Function from JavaScript Over Android Webview
Is There a JavaScript Function That Can Pad a String to Get to a Determined Length
Using Jquery to Test If an Input Has Focus
Take a Screenshot of a Webpage With JavaScript
Sum JavaScript Object Propertya Values With the Same Object Propertyb in an Array of Objects
Sending Command Line Arguments to Npm Script