When loading my page in Google Chrome, I get a vague error in the console:
Uncaught SyntaxError: Unexpected end of input
I have no idea what is causing it. How would I go about debugging this error?
This particular error is one annoying fact about v8. In most cases your JavaScript is broken in some way. For example missing a }
or something like that.
Example given, this will yield "Unexpected end of input" too:
eval('[{"test": 4}') // notice the missing ]
But the root cause of the problems seems to be that the requested JSON url has a Content-Type of text/html
which Chrome apparently tries to parse as HTML, which then results in the unexpected end of input due to the fact that the included image tags are being parsed.
Try setting the Content-Type to text/plain
I think it should fix the issues.
Nonetheless, V8 could do a better Job about telling one exactly where the input ended unexpectedly.
See my case on another similar question:
In my case, I was trying to parse an empty JSON:
JSON.parse(stringifiedJSON);
In other words, what happened was the following:
JSON.parse("");
For the record, for anyone trying to find the various causes for this error. An empty HTML5 data attribute
data-mydata = ''
causes the error too. You should check when the data value is a null string and not include the attribute at all. It goes without saying this is largely relevant to script generated HTML.
In cases where your JavaScript code is minified to a single line, another cause for this error is using //
instead of /**/
for your comments.
Bad (comments out everything after //
including the closing }
for your function)
function example() { //comment console.log('TEST'); }
Good (confines your comment)
function example() { /* comment */ console.log('TEST'); }
Trying to parse an empty JSON can be the cause of this error.
When you receive a response from the server or whatever, check first if it's not empty. For example:
function parseJSON(response) {
if (response.status === 204 || response.status === 205) {
return null;
}
return response.json();
}
Then you can fetch with:
fetch(url, options).then(parseJSON);
I faced similar problem using ui bootstrap directive for angularjs - uib-datepicker, when pressing am/pm toggle.
Error in event handler for (unknown): SyntaxError: Unexpected end of JSON input angular timepicker
Turned out it was because of plugin 'Trans-over' (which translates a word when it is clicked). Maybe my answer will help someone, because I didn't found anything on the internet.
Content-length
header specifies more bytes than the response contains, or maybe the server somehow sends invalid HTML. – tdammers<script>https://example.com/a.js</script>
and it should have been<script src="https://example.com/a.js"></script>
– Daniel Apt