Когда встречается. Допустим, вы пишете цикл for на JavaScript и вспоминаете, что там нужна переменная цикла, условие и шаг цикла:
for var i = 1; i < 10; i++ {
<span style="font-weight: 400;"> // какой-то код</span>
<span style="font-weight: 400;">}</span>
После запуска в браузере цикл падает с ошибкой:
❌ Uncaught SyntaxError: Unexpected token ‘var’
Что значит. Unexpected token означает, что интерпретатор вашего языка встретил в коде что-то неожиданное. В нашем случае это интерпретатор JavaScript, который не ожидал увидеть в этом месте слово var, поэтому остановил работу.
Причина — скорее всего, вы пропустили что-то из синтаксиса: скобку, кавычку, точку с запятой, запятую, что-то подобное. Может быть, у вас была опечатка в служебном слове и язык его не распознал.
Что делать с ошибкой Uncaught SyntaxError: Unexpected token
Когда интерпретатор не может обработать скрипт и выдаёт ошибку, он обязательно показывает номер строки, где эта ошибка произошла (в нашем случае — в первой же строке):
Если мы нажмём на надпись VM21412:1, то браузер нам сразу покажет строку с ошибкой и подчеркнёт непонятное для себя место:
По этому фрагменту сразу видно, что браузеру не нравится слово var. Что делать теперь:
- Проверьте, так ли пишется эта конструкция на вашем языке. В случае JavaScript тут не хватает скобок. Должно быть for (var i=1; i<10; i++) {}
- Посмотрите на предыдущие команды. Если там не закрыта скобка или кавычка, интерпретатор может ругаться на код немного позднее.
Попробуйте сами
Каждый из этих фрагментов кода даст ошибку Uncaught SyntaxError: Unexpected token. Попробуйте это исправить.
if (a==b) then {}
function nearby(number, today, oneday, threeday) {
if (user_today == today + 1 || user_today == today - 1)
(user_oneday == oneday + 1 || user_oneday == oneday - 1)
&& (user_threeday == threeday + 1 || user_threeday == threeday - 1)
return true
else
return false
}
var a = prompt('Зимой и летом одним цветом');
if (a == 'ель'); {
alert("верно");
} else {
alert("неверно");
}
alert(end);
I am running an AJAX call in my MooTools script, this works fine in Firefox but in Chrome I am getting a Uncaught SyntaxError: Unexpected token :
error, I cannot determine why. Commenting out code to determine where the bad code is yields nothing, I am thinking it may be a problem with the JSON being returned. Checking in the console I see the JSON returned is this:
{"votes":47,"totalvotes":90}
I don’t see any problems with it, why would this error occur?
vote.each(function(e){
e.set('send', {
onRequest : function(){
spinner.show();
},
onComplete : function(){
spinner.hide();
},
onSuccess : function(resp){
var j = JSON.decode(resp);
if (!j) return false;
var restaurant = e.getParent('.restaurant');
restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
$$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
buildRestaurantGraphs();
}
});
e.addEvent('submit', function(e){
e.stop();
this.send();
});
});
asked Jun 29, 2010 at 18:37
trobrocktrobrock
46.3k11 gold badges38 silver badges45 bronze badges
6
Seeing red errors
Uncaught SyntaxError: Unexpected token <
in your Chrome developer’s console tab is an indication of HTML in the response body.
What you’re actually seeing is your browser’s reaction to the unexpected top line <!DOCTYPE html>
from the server.
miken32
41.5k16 gold badges108 silver badges153 bronze badges
answered Oct 28, 2014 at 17:56
andy magoonandy magoon
2,8792 gold badges19 silver badges14 bronze badges
9
Just an FYI for people who might have the same problem — I just had to make my server send back the JSON as application/json and the default jQuery handler worked fine.
answered Aug 28, 2010 at 20:19
Edward AbramsEdward Abrams
9051 gold badge6 silver badges3 bronze badges
5
This has just happened to me, and the reason was none of the reasons above. I was using the jQuery command getJSON and adding callback=?
to use JSONP (as I needed to go cross-domain), and returning the JSON code {"foo":"bar"}
and getting the error.
This is because I should have included the callback data, something like jQuery17209314005577471107_1335958194322({"foo":"bar"})
Here is the PHP code I used to achieve this, which degrades if JSON (without a callback) is used:
$ret['foo'] = "bar";
finish();
function finish() {
header("content-type:application/json");
if ($_GET['callback']) {
print $_GET['callback']."(";
}
print json_encode($GLOBALS['ret']);
if ($_GET['callback']) {
print ")";
}
exit;
}
Hopefully that will help someone in the future.
answered May 2, 2012 at 11:35
Grim…Grim…
16.4k7 gold badges44 silver badges61 bronze badges
3
I have just solved the problem. There was something causing problems with a standard Request call, so this is the code I used instead:
vote.each(function(element){
element.addEvent('submit', function(e){
e.stop();
new Request.JSON({
url : e.target.action,
onRequest : function(){
spinner.show();
},
onComplete : function(){
spinner.hide();
},
onSuccess : function(resp){
var j = resp;
if (!j) return false;
var restaurant = element.getParent('.restaurant');
restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
$$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
buildRestaurantGraphs();
}
}).send(this);
});
});
If anyone knows why the standard Request object was giving me problems I would love to know.
answered Jun 30, 2010 at 20:27
trobrocktrobrock
46.3k11 gold badges38 silver badges45 bronze badges
6
I thought I’d add my issue and resolution to the list.
I was getting: Uncaught SyntaxError: Unexpected token <
and the error was pointing to this line in my ajax success statement:
var total = $.parseJSON(response);
I later found that in addition to the json results, there was HTML being sent with the response because I had an error in my PHP. When you get an error in PHP you can set it to warn you with huge orange tables and those tables were what was throwing off the JSON.
I found that out by just doing a console.log(response)
in order to see what was actually being sent. If it’s an issue with the JSON data, just try to see if you can do a console.log or some other statement that will allow you to see what is sent and what is received.
answered Dec 19, 2013 at 2:50
neuquenneuquen
3,96115 gold badges58 silver badges78 bronze badges
2
When you request your JSON file, server returns JavaScript Content-Type
header (text/javascript
) instead of JSON (application/json
).
According to MooTools docs:
Responses with javascript content-type will be evaluated automatically.
In result MooTools tries to evaluate your JSON as JavaScript, and when you try to evaluate such JSON:
{"votes":47,"totalvotes":90}
as JavaScript, parser treats {
and }
as a block scope instead of object notation. It is the same as evaluating following «code»:
"votes":47,"totalvotes":90
As you can see, :
is totally unexpected there.
The solution is to set correct Content-Type
header for the JSON file. If you save it with .json
extension, your server should do it by itself.
answered Dec 29, 2015 at 14:38
It sounds like your response is being evaluated somehow. This gives the same error in Chrome:
var resp = '{"votes":47,"totalvotes":90}';
eval(resp);
This is due to the braces ‘{…}’ being interpreted by javascript as a code block and not an object literal as one might expect.
I would look at the JSON.decode() function and see if there is an eval in there.
Similar issue here:
Eval() = Unexpected token : error
answered Aug 13, 2015 at 19:39
ZectbumoZectbumo
3,7781 gold badge31 silver badges25 bronze badges
This happened to me today as well. I was using EF and returning an Entity in response to an AJAX call. The virtual properties on my entity was causing a cyclical dependency error that was not being detected on the server. By adding the [ScriptIgnore] attribute on the virtual properties, the problem was fixed.
Instead of using the ScriptIgnore attribute, it would probably be better to just return a DTO.
answered Mar 24, 2016 at 22:31
DarylDaryl
6101 gold badge7 silver badges17 bronze badges
This happened to because I have a rule setup in my express server to route any 404 back to /#
plus whatever the original request was. Allowing the angular router/js to handle the request. If there’s no js route to handle that path, a request to /#/whatever
is made to the server, which is just a request for /
, the entire webpage.
So for example if I wanted to make a request for /correct/somejsfile.js
but I miss typed it to /wrong/somejsfile.js
the request is made to the server. That location/file does not exist, so the server responds with a 302 location: /#/wrong/somejsfile.js
. The browser happily follows the redirect and the entire webpage is returned. The browser parses the page as js and you get
Uncaught SyntaxError: Unexpected token <
So to help find the offending path/request look for 302 requests.
Hope that helps someone.
answered Jan 26, 2018 at 21:14
JerinawJerinaw
5,2107 gold badges40 silver badges54 bronze badges
If nothing makes sense, this error can also be caused by PHP Error that is embedded inside html/javascript, such as the one below
<br />
<b>Deprecated</b>: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in <b>C:Projectsrwpdemoensuperge.php</b> on line <b>54</b><br />
var zNodes =[{ id:1, pId:0, name:"ACE", url: "/ace1.php", target:"_self", open:true}
Not the <br />
etc in the code that are inserted into html by PHP is causing the error. To fix this kind of error (suppress warning), used this code in the start
error_reporting(E_ERROR | E_PARSE);
To view, right click on page, «view source» and then examine complete html to spot this error.
answered Nov 9, 2018 at 19:45
TheTechGuyTheTechGuy
16.4k16 gold badges114 silver badges135 bronze badges
I got this error because I was missing the type attribute in script tag.
Initially I was using but when I added the type attribute inside the script tag then my issue is resolved
answered Jul 28, 2022 at 15:37
Hemant Hemant
955 bronze badges
«Uncaught SyntaxError: Unexpected token» error appearance when your data return wrong json format, in some case, you don’t know you got wrong json format.
please check it with alert(); function
onSuccess : function(resp){
alert(resp);
}
your message received should be: {«firstName»:»John», «lastName»:»Doe»}
and then you can use code below
onSuccess : function(resp){
var j = JSON.decode(resp); // but in my case i'm using: JSON.parse(resp);
}
with out error «Uncaught SyntaxError: Unexpected token«
but if you get wrong json format
ex:
…{«firstName»:»John», «lastName»:»Doe»}
or
Undefined variable: errCapt in .... on line<b>65</b><br/>{"firstName":"John", "lastName":"Doe"}
so that you got wrong json format, please fix it before you JSON.decode or JSON.parse
answered Mar 17, 2015 at 10:11
RainRain
6016 silver badges10 bronze badges
1
I had the same problem and it turned out that the Json returned from the server
wasn’t valid Json-P. If you don’t use the call as a crossdomain call use regular Json.
answered Nov 13, 2013 at 8:31
jakobjakob
5,9797 gold badges64 silver badges103 bronze badges
1
My mistake was forgetting single/double quotation around url in javascript:
so wrong code was:
window.location = https://google.com;
and correct code:
window.location = "https://google.com";
answered Apr 11, 2020 at 8:03
In my case putting /
at the beginning of the src
of scripts or href
of stylesheets solved the issue.
answered Jul 1, 2021 at 13:02
1
I got a «SyntaxError: Unexpected token I
» when I used jQuery.getJSON()
to try to de-serialize a floating point value of Infinity
, encoded as INF
, which is illegal in JSON.
answered Jul 18, 2013 at 19:52
Mark CidadeMark Cidade
98.2k31 gold badges223 silver badges236 bronze badges
1
In my case i ran into the same error, while running spring mvc application due to wrong mapping in my mvc controller
@RequestMapping(name="/private/updatestatus")
i changed the above mapping to
@RequestMapping("/private/updatestatus")
or
@RequestMapping(value="/private/updatestatus",method = RequestMethod.GET)
answered Sep 26, 2015 at 3:58
For me the light bulb went on when I viewed the source to the page inside the Chrome browser. I had an extra bracket in an if statement. You’ll immediately see the red circle with a cross in it on the failing line. It’s a rather unhelpful error message, because the the Uncaught Syntax Error: Unexpected token makes no reference to a line number when it first appears in the console of Chrome.
answered Jun 21, 2017 at 13:47
JGFMKJGFMK
8,3054 gold badges55 silver badges92 bronze badges
I did Wrong in this
`var fs = require('fs');
var fs.writeFileSync(file, configJSON);`
Already I intialized the fs
variable.But again i put var
in the second line.This one also gives that kind of error…
answered Jul 21, 2017 at 6:13
Janen RJanen R
72910 silver badges21 bronze badges
For those experiencing this in AngularJs 1.4.6 or similar, my problem was with angular not finding my template because the file at the templateUrl
(path) I provided couldn’t be found. I just had to provide a reachable path and the problem went away.
answered Feb 2, 2018 at 5:08
lwdthe1lwdthe1
9421 gold badge14 silver badges15 bronze badges
1
In my case it was a mistaken url (not existing), so maybe your ‘send’ in second line should be other…
answered Dec 20, 2018 at 18:01
This error might also mean a missing colon
or :
in your code.
answered Oct 6, 2020 at 10:15
Cons BulaquenaCons Bulaquena
2,0732 gold badges26 silver badges24 bronze badges
Facing JS issues repetitively I am working on a Ckeditor apply on my xblock package. please suggest to me if anyone helping me out. Using OpenEdx, Javascript, xblock
xblock.js:158 SyntaxError: Unexpected token '=>'
at eval (<anonymous>)
at Function.globalEval (jquery.js:343)
at domManip (jquery.js:5291)
at jQuery.fn.init.append (jquery.js:5431)
at child.loadResource (xblock.js:236)
at applyResource (xblock.js:199)
at Object.<anonymous> (xblock.js:202)
at fire (jquery.js:3187)
at Object.add [as done] (jquery.js:3246)
at applyResource (xblock.js:201) "SyntaxError: Unexpected token '=>'n at eval (<anonymous>)n at Function.globalEval (http://localhost:18010/static/studio/common/js/vendor/jquery.js:343:5)n at domManip (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5291:15)n at jQuery.fn.init.append (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5431:10)n at child.loadResource (http://localhost:18010/static/studio/bundles/commons.js:5091:27)n at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5054:36)n at Object.<anonymous> (http://localhost:18010/static/studio/bundles/commons.js:5057:25)n at fire (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3187:31)n at Object.add [as done] (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3246:7)n at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5056:29)"
answered Nov 13, 2021 at 18:47
Late to the party but my solution was to specify the dataType as json. Alternatively make sure you do not set jsonp: true.
answered May 9, 2022 at 9:17
Try this to ignore this issue:
Cypress.on('uncaught:exception', (err, runnable) => {
return false;
});
answered Sep 9, 2022 at 11:17
The best practice is to install all your dependencies using npm install
or can install all dependencies dedicatedly
answered Mar 13 at 4:13
Uncaught SyntaxError: Unexpected token }
Chrome gaved me the error for this sample code:
<div class="file-square" onclick="window.location = " ?dir=zzz">
<div class="square-icon"></div>
<div class="square-text">zzz</div>
</div>
and solved it fixing the onclick to be like
... onclick="window.location = '?dir=zzz'" ...
But the error has nothing to do with the problem..
answered Sep 24, 2013 at 9:21
ungalcrysungalcrys
5,2042 gold badges39 silver badges23 bronze badges
1
I am running an AJAX call in my MooTools script, this works fine in Firefox but in Chrome I am getting a Uncaught SyntaxError: Unexpected token :
error, I cannot determine why. Commenting out code to determine where the bad code is yields nothing, I am thinking it may be a problem with the JSON being returned. Checking in the console I see the JSON returned is this:
{"votes":47,"totalvotes":90}
I don’t see any problems with it, why would this error occur?
vote.each(function(e){
e.set('send', {
onRequest : function(){
spinner.show();
},
onComplete : function(){
spinner.hide();
},
onSuccess : function(resp){
var j = JSON.decode(resp);
if (!j) return false;
var restaurant = e.getParent('.restaurant');
restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
$$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
buildRestaurantGraphs();
}
});
e.addEvent('submit', function(e){
e.stop();
this.send();
});
});
asked Jun 29, 2010 at 18:37
trobrocktrobrock
46.3k11 gold badges38 silver badges45 bronze badges
6
Seeing red errors
Uncaught SyntaxError: Unexpected token <
in your Chrome developer’s console tab is an indication of HTML in the response body.
What you’re actually seeing is your browser’s reaction to the unexpected top line <!DOCTYPE html>
from the server.
miken32
41.5k16 gold badges108 silver badges153 bronze badges
answered Oct 28, 2014 at 17:56
andy magoonandy magoon
2,8792 gold badges19 silver badges14 bronze badges
9
Just an FYI for people who might have the same problem — I just had to make my server send back the JSON as application/json and the default jQuery handler worked fine.
answered Aug 28, 2010 at 20:19
Edward AbramsEdward Abrams
9051 gold badge6 silver badges3 bronze badges
5
This has just happened to me, and the reason was none of the reasons above. I was using the jQuery command getJSON and adding callback=?
to use JSONP (as I needed to go cross-domain), and returning the JSON code {"foo":"bar"}
and getting the error.
This is because I should have included the callback data, something like jQuery17209314005577471107_1335958194322({"foo":"bar"})
Here is the PHP code I used to achieve this, which degrades if JSON (without a callback) is used:
$ret['foo'] = "bar";
finish();
function finish() {
header("content-type:application/json");
if ($_GET['callback']) {
print $_GET['callback']."(";
}
print json_encode($GLOBALS['ret']);
if ($_GET['callback']) {
print ")";
}
exit;
}
Hopefully that will help someone in the future.
answered May 2, 2012 at 11:35
Grim…Grim…
16.4k7 gold badges44 silver badges61 bronze badges
3
I have just solved the problem. There was something causing problems with a standard Request call, so this is the code I used instead:
vote.each(function(element){
element.addEvent('submit', function(e){
e.stop();
new Request.JSON({
url : e.target.action,
onRequest : function(){
spinner.show();
},
onComplete : function(){
spinner.hide();
},
onSuccess : function(resp){
var j = resp;
if (!j) return false;
var restaurant = element.getParent('.restaurant');
restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
$$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
buildRestaurantGraphs();
}
}).send(this);
});
});
If anyone knows why the standard Request object was giving me problems I would love to know.
answered Jun 30, 2010 at 20:27
trobrocktrobrock
46.3k11 gold badges38 silver badges45 bronze badges
6
I thought I’d add my issue and resolution to the list.
I was getting: Uncaught SyntaxError: Unexpected token <
and the error was pointing to this line in my ajax success statement:
var total = $.parseJSON(response);
I later found that in addition to the json results, there was HTML being sent with the response because I had an error in my PHP. When you get an error in PHP you can set it to warn you with huge orange tables and those tables were what was throwing off the JSON.
I found that out by just doing a console.log(response)
in order to see what was actually being sent. If it’s an issue with the JSON data, just try to see if you can do a console.log or some other statement that will allow you to see what is sent and what is received.
answered Dec 19, 2013 at 2:50
neuquenneuquen
3,96115 gold badges58 silver badges78 bronze badges
2
When you request your JSON file, server returns JavaScript Content-Type
header (text/javascript
) instead of JSON (application/json
).
According to MooTools docs:
Responses with javascript content-type will be evaluated automatically.
In result MooTools tries to evaluate your JSON as JavaScript, and when you try to evaluate such JSON:
{"votes":47,"totalvotes":90}
as JavaScript, parser treats {
and }
as a block scope instead of object notation. It is the same as evaluating following «code»:
"votes":47,"totalvotes":90
As you can see, :
is totally unexpected there.
The solution is to set correct Content-Type
header for the JSON file. If you save it with .json
extension, your server should do it by itself.
answered Dec 29, 2015 at 14:38
It sounds like your response is being evaluated somehow. This gives the same error in Chrome:
var resp = '{"votes":47,"totalvotes":90}';
eval(resp);
This is due to the braces ‘{…}’ being interpreted by javascript as a code block and not an object literal as one might expect.
I would look at the JSON.decode() function and see if there is an eval in there.
Similar issue here:
Eval() = Unexpected token : error
answered Aug 13, 2015 at 19:39
ZectbumoZectbumo
3,7781 gold badge31 silver badges25 bronze badges
This happened to me today as well. I was using EF and returning an Entity in response to an AJAX call. The virtual properties on my entity was causing a cyclical dependency error that was not being detected on the server. By adding the [ScriptIgnore] attribute on the virtual properties, the problem was fixed.
Instead of using the ScriptIgnore attribute, it would probably be better to just return a DTO.
answered Mar 24, 2016 at 22:31
DarylDaryl
6101 gold badge7 silver badges17 bronze badges
This happened to because I have a rule setup in my express server to route any 404 back to /#
plus whatever the original request was. Allowing the angular router/js to handle the request. If there’s no js route to handle that path, a request to /#/whatever
is made to the server, which is just a request for /
, the entire webpage.
So for example if I wanted to make a request for /correct/somejsfile.js
but I miss typed it to /wrong/somejsfile.js
the request is made to the server. That location/file does not exist, so the server responds with a 302 location: /#/wrong/somejsfile.js
. The browser happily follows the redirect and the entire webpage is returned. The browser parses the page as js and you get
Uncaught SyntaxError: Unexpected token <
So to help find the offending path/request look for 302 requests.
Hope that helps someone.
answered Jan 26, 2018 at 21:14
JerinawJerinaw
5,2107 gold badges40 silver badges54 bronze badges
If nothing makes sense, this error can also be caused by PHP Error that is embedded inside html/javascript, such as the one below
<br />
<b>Deprecated</b>: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in <b>C:Projectsrwpdemoensuperge.php</b> on line <b>54</b><br />
var zNodes =[{ id:1, pId:0, name:"ACE", url: "/ace1.php", target:"_self", open:true}
Not the <br />
etc in the code that are inserted into html by PHP is causing the error. To fix this kind of error (suppress warning), used this code in the start
error_reporting(E_ERROR | E_PARSE);
To view, right click on page, «view source» and then examine complete html to spot this error.
answered Nov 9, 2018 at 19:45
TheTechGuyTheTechGuy
16.4k16 gold badges114 silver badges135 bronze badges
I got this error because I was missing the type attribute in script tag.
Initially I was using but when I added the type attribute inside the script tag then my issue is resolved
answered Jul 28, 2022 at 15:37
Hemant Hemant
955 bronze badges
«Uncaught SyntaxError: Unexpected token» error appearance when your data return wrong json format, in some case, you don’t know you got wrong json format.
please check it with alert(); function
onSuccess : function(resp){
alert(resp);
}
your message received should be: {«firstName»:»John», «lastName»:»Doe»}
and then you can use code below
onSuccess : function(resp){
var j = JSON.decode(resp); // but in my case i'm using: JSON.parse(resp);
}
with out error «Uncaught SyntaxError: Unexpected token«
but if you get wrong json format
ex:
…{«firstName»:»John», «lastName»:»Doe»}
or
Undefined variable: errCapt in .... on line<b>65</b><br/>{"firstName":"John", "lastName":"Doe"}
so that you got wrong json format, please fix it before you JSON.decode or JSON.parse
answered Mar 17, 2015 at 10:11
RainRain
6016 silver badges10 bronze badges
1
I had the same problem and it turned out that the Json returned from the server
wasn’t valid Json-P. If you don’t use the call as a crossdomain call use regular Json.
answered Nov 13, 2013 at 8:31
jakobjakob
5,9797 gold badges64 silver badges103 bronze badges
1
My mistake was forgetting single/double quotation around url in javascript:
so wrong code was:
window.location = https://google.com;
and correct code:
window.location = "https://google.com";
answered Apr 11, 2020 at 8:03
In my case putting /
at the beginning of the src
of scripts or href
of stylesheets solved the issue.
answered Jul 1, 2021 at 13:02
1
I got a «SyntaxError: Unexpected token I
» when I used jQuery.getJSON()
to try to de-serialize a floating point value of Infinity
, encoded as INF
, which is illegal in JSON.
answered Jul 18, 2013 at 19:52
Mark CidadeMark Cidade
98.2k31 gold badges223 silver badges236 bronze badges
1
In my case i ran into the same error, while running spring mvc application due to wrong mapping in my mvc controller
@RequestMapping(name="/private/updatestatus")
i changed the above mapping to
@RequestMapping("/private/updatestatus")
or
@RequestMapping(value="/private/updatestatus",method = RequestMethod.GET)
answered Sep 26, 2015 at 3:58
For me the light bulb went on when I viewed the source to the page inside the Chrome browser. I had an extra bracket in an if statement. You’ll immediately see the red circle with a cross in it on the failing line. It’s a rather unhelpful error message, because the the Uncaught Syntax Error: Unexpected token makes no reference to a line number when it first appears in the console of Chrome.
answered Jun 21, 2017 at 13:47
JGFMKJGFMK
8,3054 gold badges55 silver badges92 bronze badges
I did Wrong in this
`var fs = require('fs');
var fs.writeFileSync(file, configJSON);`
Already I intialized the fs
variable.But again i put var
in the second line.This one also gives that kind of error…
answered Jul 21, 2017 at 6:13
Janen RJanen R
72910 silver badges21 bronze badges
For those experiencing this in AngularJs 1.4.6 or similar, my problem was with angular not finding my template because the file at the templateUrl
(path) I provided couldn’t be found. I just had to provide a reachable path and the problem went away.
answered Feb 2, 2018 at 5:08
lwdthe1lwdthe1
9421 gold badge14 silver badges15 bronze badges
1
In my case it was a mistaken url (not existing), so maybe your ‘send’ in second line should be other…
answered Dec 20, 2018 at 18:01
This error might also mean a missing colon
or :
in your code.
answered Oct 6, 2020 at 10:15
Cons BulaquenaCons Bulaquena
2,0732 gold badges26 silver badges24 bronze badges
Facing JS issues repetitively I am working on a Ckeditor apply on my xblock package. please suggest to me if anyone helping me out. Using OpenEdx, Javascript, xblock
xblock.js:158 SyntaxError: Unexpected token '=>'
at eval (<anonymous>)
at Function.globalEval (jquery.js:343)
at domManip (jquery.js:5291)
at jQuery.fn.init.append (jquery.js:5431)
at child.loadResource (xblock.js:236)
at applyResource (xblock.js:199)
at Object.<anonymous> (xblock.js:202)
at fire (jquery.js:3187)
at Object.add [as done] (jquery.js:3246)
at applyResource (xblock.js:201) "SyntaxError: Unexpected token '=>'n at eval (<anonymous>)n at Function.globalEval (http://localhost:18010/static/studio/common/js/vendor/jquery.js:343:5)n at domManip (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5291:15)n at jQuery.fn.init.append (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5431:10)n at child.loadResource (http://localhost:18010/static/studio/bundles/commons.js:5091:27)n at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5054:36)n at Object.<anonymous> (http://localhost:18010/static/studio/bundles/commons.js:5057:25)n at fire (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3187:31)n at Object.add [as done] (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3246:7)n at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5056:29)"
answered Nov 13, 2021 at 18:47
Late to the party but my solution was to specify the dataType as json. Alternatively make sure you do not set jsonp: true.
answered May 9, 2022 at 9:17
Try this to ignore this issue:
Cypress.on('uncaught:exception', (err, runnable) => {
return false;
});
answered Sep 9, 2022 at 11:17
The best practice is to install all your dependencies using npm install
or can install all dependencies dedicatedly
answered Mar 13 at 4:13
Uncaught SyntaxError: Unexpected token }
Chrome gaved me the error for this sample code:
<div class="file-square" onclick="window.location = " ?dir=zzz">
<div class="square-icon"></div>
<div class="square-text">zzz</div>
</div>
and solved it fixing the onclick to be like
... onclick="window.location = '?dir=zzz'" ...
But the error has nothing to do with the problem..
answered Sep 24, 2013 at 9:21
ungalcrysungalcrys
5,2042 gold badges39 silver badges23 bronze badges
1
Introduction
A common issue that I see when working with front-end JavaScript heavy apps is the dreaded “SyntaxError Unexpected Token in JSON” error! Now this error can be of the form:
SyntaxError: Unexpected token < in JSON at position 0
SyntaxError: Unexpected end of JSON input
syntaxerror: unexpected token '<', "<!doctype "... is not valid json
The error “SyntaxError Unexpected Token in JSON” appears when you try to parse content (for example — data from a database, api, etc), but the content itself is not JSON (could be XML, HTML, CSV) or invalid JSON containing unescaped characters, missing commas and brackets.
There are a few things you can try to fix this error:
-
Check that the content you are trying to parse is JSON format and not HTML or XML
-
Verify that there are no missing or extra commas.
-
Make sure to check for unescaped special characters.
-
Check for mismatched brackets or quotes.
-
Make sure the JSON is valid. You can use a tool like JSONLint to validate your JSON and check for any errors.
1. Check that the content you are trying to parse is JSON format and not HTML or XML
A common reason why the error “SyntaxError Unexpected Token in JSON” comes up is that we are trying to parse content that is not even JSON.
Consider the following front-end JavaScript code:
fetch('https://localhost:3000/data')
.then(response => response.json())
.then(data => {
console.log(data);
// Use the data here
})
In the above example, the fetch() function is being used to retrieve data from a API that returns JSON format — in this case https://localhost:3000/data.
The fetch()
function then returns a promise, and when that promise resolves, we handle that with the response.json()
method. This just takes our JSON response and converts it to a JSON object to be used!
After that we just console.log out the data object
Now for the server-side of things, look on to our Node JS route that returns the JSON /data
var http = require('http');
var app = http.createServer(function(req,res){
res.setHeader('Content-Type', 'text/html'); ❌ Not returning JSON.
res.end(JSON.stringify({ a: 1 }));
});
app.listen(3000);
We can see that it is setting the Header as text/html
. This will give you the error:
syntaxerror: unexpected token '<', "<!doctype "... is not valid json
This is because we are trying to parse the content with JSON.parse()
or in our case response.json()
and receiving a HTML file!
To fix this, we just need to change the returned header to res.setHeader('Content-Type', 'application/json')
:
...
var app = http.createServer(function(req,res){
res.setHeader('Content-Type', 'application/json'); ✔️ Returning JSON.
res.end(JSON.stringify({ a: 1 }));
});
...
Whats
Content-Type
request header anyway?Pretty much every resource on the internet will need to have a type (similar to how your file system contains file types like images, videos, text, etc).
This is known as a MIME type (Multipurpose Internet Mail Extension)Browsers need to know what content type a resource is so that it can best handle it. Most modern browsers are becoming good at figuring out which content type a resource is, but its not always 100% correct.
That is why still need to explicitly specify our request header
content-type
!
syntaxerror: unexpected token ‘<’, “<!doctype “… is not valid json
This error also comes up when your API is returning invalid error pages such as 404/500 HTML pages. Since HTML usually starts with a “less than” tag symbol (<
) and JSON is not valid with <
tags, it will through this error.
For example, when everything is working find, your node API will happily return JSON. However when it fails with a 500 internal error, it could return a custom HTML error page!
In this case, when you try to do JSON.parse(data)
you will get the syntaxerror: unexpected token '<', "<!doctype "... is not valid json
.
Additionally, check that you are calling the correct API url. As an example, lets say the API that returns JSON is using the /data
route. If you misspelt this, you could be redirected to a 404 HTML page instead!
Tip: Use appropriate error handlers for non-JSON data
If you are using fetch()
to retrieve your data, we can add a catch handler to give meaningful error messages to the user:
fetch('https://localhost:3000/data')
.then(response => response.json())
.then(data => {
console.log(data);
// Use the data here
})
.catch(error => console.error(error)); /*✔️ Friendly error message for debugging! */
If you are using JSON.parse()
we can do this in a try/catch block as follows:
try {
JSON.parse(data);
}
catch (error) {
console.log('Error parsing JSON:', error, data); /*✔️ Friendly message for debugging ! */
}
JSON objects and arrays should have a comma between each item, except for the last one.
{
"name": "John Smith"
"age": 30
"address": {
"street": "123 Main St"
"city": "Anytown"
"state": "USA"
}
}
This JSON object will throw a “syntaxerror unexpected token” error because there is no comma between “John Smith” and “age”, and also between “Anytown” and “state”.
To fix this, you would add commas as follows:
{
"name": "John Smith",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "USA"
}
}
By adding commas between each item except for the last one, the JSON object is now in the correct format and should parse without error.
3. Make sure to use double quotes and escape special characters.
JSON strings must be wrapped in double quotes, and any special characters within the string must be properly escaped. Consider the following example:
{
"name": "John Smith",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "USA"
},
"message": "It's a lovely day"
}
When we try to parse this with JSON.parse
, we will get the error: SyntaxError: Invalid or unexpected token.
The problem is with the following line using a apostrophe:
"message": "It's a lovely day"
{
"name": "John Smith",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "USA"
},
"message": "It's a lovely day"
}
As we can see, this will fix our error since we escape the aspostrophe as such:
"message": "It's a lovely day"
4. Check for mismatched brackets or quotes.
Make sure all brackets and quotes are properly closed and match up.
{
"name": "John Smith",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "USA"
}
In this example, the JSON object is missing a closing curly bracket, which indicates the end of the object. Because of this, it will throw a “syntaxerror unexpected token” error.
To fix this, you would add the missing closing curly bracket as follows:
{
"name": "John Smith",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "USA"
}
}
If you want to be sure that the JSON is valid, we can try to use the NPM package JSONLint (https://github.com/zaach/jsonlint)
We can install jsonlint with npm as follows:
- Open up the terminal
- Run NPM install
npm install jsonlint -g
- We can then validate a file like so:
jsonlint myfile.json
Summary
In this article I went over the SyntaxError: Unexpected token < in JSON at position 0 when dealing with parsing JSON with fetch
or JSON.parse
. This error is mainly due to the JSON not being in correct format or the content that we are trying to parse is not even JSON.
In the case of JSON being invalid, make sure to check for unescaped characters, missing commas, non-matching brackets and quotes.
To be really sure, check the JSON with tools like JSONLint to validate!
In the case of the content you are trying to parse being non-JSON such as HTML, check your API to make sure that error pages return JSON correctly instead of HTML pages.
Similar to other programming languages, JavaScript has its own syntax. The error “Uncaught SyntaxError: Unexpected token” shows that your code does not match the JavaScript syntax. It could be due to some typos in your code, a mistake when including a JavaScript file into HTML, or a wrong HTML in JavaScript code.
The reason for the error “Uncaught SyntaxError: Unexpected token”
JavaScript has its own syntax for literals, variables, operators, expressions, keywords, and comments. When running your code, the JavaScript runtime tries to parse the code based on the JavaScript syntax. When it cannot do, it throws an error “Uncaught SyntaxError: Unexpected token” with the position where the error occurs. Because it is a syntax error, there are many situations that can cause the error. Usually, it is due to you having an extra or missing a character or punctuation. Another reason is that you accidentally put some HTML code in your JavaScript code in the wrong way. You can reproduce the error with this example. You can easily see that I have an extra close bracket ‘)’, which causes the error.
Example code:
if (true)) {
console.log('It is true');
}
Output:
if (true)) {
^
SyntaxError: Unexpected token ')'
Example 1: Invalid syntax causes the error
There are many ways that your code has an invalid syntax that cause the error. Here I have an example in that I missed the open and close brackets of the if condition.
Example code:
let a = 1;
let b = 2;
let c = 3;
if (a + b == c) || (a == c) {
console.log('a is ok');
}
Output:
if (a + b == c) || (a == c) {
^^
SyntaxError: Unexpected token '||'
The error message will also show which is the unexpected token so that you can easily fix this error. You can also avoid invalid syntax in your code by using a suitable JavaScript snippet extension for your code editor, such as Visual Studio Code, Sublime Text, Atom,…
Example 2: Include a file that is not JavaScript to the script tag
Another common mistake that causes the error is including something that is not a valid JavaScript file in the script tag, maybe it is an HTML file.
Example code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page 1</title>
<script src="index.html"></script>
</head>
<body>
Some content!
</body>
</html>
Output:
Uncaught SyntaxError: Unexpected token '<' (at index.html:1:1)
When you load the HTML code above in your browser, you will get the error in the console. Of course, to fix this error, you need to specify the right path to the JavaScript file that you want to use.
Example 3: Invalid HTML code in JavaScript code
Sometimes, you have some HTML code in your JavaScript code, for example, when you want to set the innerHTML value for an element. Make sure you use your HTML code as a string by putting it in the quotes or you will get a syntax error.
Example code:
let message = document.getElementById("message");
// This's right
message.innerHTML = '<div>Message content</div>';
// This cause an error
message.innerHTML = <div>Message content</div>;
Output:
message.innerHTML = <div>Message content</div>;
^
SyntaxError: Unexpected token '<'
Summary
In this tutorial, I have some examples to show you how to solve the error “Uncaught SyntaxError: Unexpected token” in JavaScript. You need to make sure your code has valid JavaScript syntax. Also, pay attention to having the right code when you use JavaScript with HTML.
Maybe you are interested in similar errors:
- Uncaught SyntaxError Unexpected end of input
- Unexpected token u in JSON at position 0
- unexpected token o in json at position 1 error in js
- Cannot read properties of undefined
Hello, I’m Joseph Stanley. My major is IT and I want to share programming languages to you. If you have difficulty with JavaScript, TypeScript, C#, Python, C, C++, Java, let’s follow my articles. They are helpful for you.
Job: Developer
Name of the university: HUST
Major: IT
Programming Languages: JavaScript, TypeScript, C#, Python, C, C++, Java