“SyntaxError: Unexpected token < in JSON at position 0”
In a React app component which handles Facebook-like content feeds, I am running into an error:
Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0
I ran into a similar error which turned out to be a typo in the HTML within the render function, but that doesn't seem to be the case here.
More confusingly, I rolled the code back to an earlier, known-working version and I'm still getting the error.
Feed.js:
import React from 'react';
var ThreadForm = React.createClass({
getInitialState: function () {
return {author: '',
text: '',
included: '',
victim: ''
}
},
handleAuthorChange: function (e) {
this.setState({author: e.target.value})
},
handleTextChange: function (e) {
this.setState({text: e.target.value})
},
handleIncludedChange: function (e) {
this.setState({included: e.target.value})
},
handleVictimChange: function (e) {
this.setState({victim: e.target.value})
},
handleSubmit: function (e) {
e.preventDefault()
var author = this.state.author.trim()
var text = this.state.text.trim()
var included = this.state.included.trim()
var victim = this.state.victim.trim()
if (!text || !author || !included || !victim) {
return
}
this.props.onThreadSubmit({author: author,
text: text,
included: included,
victim: victim
})
this.setState({author: '',
text: '',
included: '',
victim: ''
})
},
render: function () {
return (
<form className="threadForm" onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Your name"
value={this.state.author}
onChange={this.handleAuthorChange} />
<input
type="text"
placeholder="Say something..."
value={this.state.text}
onChange={this.handleTextChange} />
<input
type="text"
placeholder="Name your victim"
value={this.state.victim}
onChange={this.handleVictimChange} />
<input
type="text"
placeholder="Who can see?"
value={this.state.included}
onChange={this.handleIncludedChange} />
<input type="submit" value="Post" />
</form>
)
}
})
var ThreadsBox = React.createClass({
loadThreadsFromServer: function () {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function (data) {
this.setState({data: data})
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString())
}.bind(this)
})
},
handleThreadSubmit: function (thread) {
var threads = this.state.data
var newThreads = threads.concat([thread])
this.setState({data: newThreads})
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: thread,
success: function (data) {
this.setState({data: data})
}.bind(this),
error: function (xhr, status, err) {
this.setState({data: threads})
console.error(this.props.url, status, err.toString())
}.bind(this)
})
},
getInitialState: function () {
return {data: }
},
componentDidMount: function () {
this.loadThreadsFromServer()
setInterval(this.loadThreadsFromServer, this.props.pollInterval)
},
render: function () {
return (
<div className="threadsBox">
<h1>Feed</h1>
<div>
<ThreadForm onThreadSubmit={this.handleThreadSubmit} />
</div>
</div>
)
}
})
module.exports = ThreadsBox
In Chrome developer tools, the error seems to be coming from this function:
loadThreadsFromServer: function loadThreadsFromServer() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function (data) {
this.setState({ data: data });
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
with the line console.error(this.props.url, status, err.toString()
underlined.
Since it looks like the error seems to have something to do with pulling JSON data from the server, I tried starting from a blank db, but the error persists. The error seems to be called in an infinite loop presumably as React continuously tries to connect to the server and eventually crashes the browser.
EDIT:
I've checked the server response with Chrome dev tools and Chrome REST client, and the data appears to be proper JSON.
EDIT 2:
It appears that though the intended API endpoint is indeed returning the correct JSON data and format, React is polling http://localhost:3000/?_=1463499798727
instead of the expected http://localhost:3001/api/threads
.
I am running a webpack hot-reload server on port 3000 with the express app running on port 3001 to return the backend data. What's frustrating here is that this was working correctly the last time I worked on it and can't find what I could have possibly changed to break it.
javascript jquery json reactjs
|
show 1 more comment
In a React app component which handles Facebook-like content feeds, I am running into an error:
Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0
I ran into a similar error which turned out to be a typo in the HTML within the render function, but that doesn't seem to be the case here.
More confusingly, I rolled the code back to an earlier, known-working version and I'm still getting the error.
Feed.js:
import React from 'react';
var ThreadForm = React.createClass({
getInitialState: function () {
return {author: '',
text: '',
included: '',
victim: ''
}
},
handleAuthorChange: function (e) {
this.setState({author: e.target.value})
},
handleTextChange: function (e) {
this.setState({text: e.target.value})
},
handleIncludedChange: function (e) {
this.setState({included: e.target.value})
},
handleVictimChange: function (e) {
this.setState({victim: e.target.value})
},
handleSubmit: function (e) {
e.preventDefault()
var author = this.state.author.trim()
var text = this.state.text.trim()
var included = this.state.included.trim()
var victim = this.state.victim.trim()
if (!text || !author || !included || !victim) {
return
}
this.props.onThreadSubmit({author: author,
text: text,
included: included,
victim: victim
})
this.setState({author: '',
text: '',
included: '',
victim: ''
})
},
render: function () {
return (
<form className="threadForm" onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Your name"
value={this.state.author}
onChange={this.handleAuthorChange} />
<input
type="text"
placeholder="Say something..."
value={this.state.text}
onChange={this.handleTextChange} />
<input
type="text"
placeholder="Name your victim"
value={this.state.victim}
onChange={this.handleVictimChange} />
<input
type="text"
placeholder="Who can see?"
value={this.state.included}
onChange={this.handleIncludedChange} />
<input type="submit" value="Post" />
</form>
)
}
})
var ThreadsBox = React.createClass({
loadThreadsFromServer: function () {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function (data) {
this.setState({data: data})
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString())
}.bind(this)
})
},
handleThreadSubmit: function (thread) {
var threads = this.state.data
var newThreads = threads.concat([thread])
this.setState({data: newThreads})
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: thread,
success: function (data) {
this.setState({data: data})
}.bind(this),
error: function (xhr, status, err) {
this.setState({data: threads})
console.error(this.props.url, status, err.toString())
}.bind(this)
})
},
getInitialState: function () {
return {data: }
},
componentDidMount: function () {
this.loadThreadsFromServer()
setInterval(this.loadThreadsFromServer, this.props.pollInterval)
},
render: function () {
return (
<div className="threadsBox">
<h1>Feed</h1>
<div>
<ThreadForm onThreadSubmit={this.handleThreadSubmit} />
</div>
</div>
)
}
})
module.exports = ThreadsBox
In Chrome developer tools, the error seems to be coming from this function:
loadThreadsFromServer: function loadThreadsFromServer() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function (data) {
this.setState({ data: data });
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
with the line console.error(this.props.url, status, err.toString()
underlined.
Since it looks like the error seems to have something to do with pulling JSON data from the server, I tried starting from a blank db, but the error persists. The error seems to be called in an infinite loop presumably as React continuously tries to connect to the server and eventually crashes the browser.
EDIT:
I've checked the server response with Chrome dev tools and Chrome REST client, and the data appears to be proper JSON.
EDIT 2:
It appears that though the intended API endpoint is indeed returning the correct JSON data and format, React is polling http://localhost:3000/?_=1463499798727
instead of the expected http://localhost:3001/api/threads
.
I am running a webpack hot-reload server on port 3000 with the express app running on port 3001 to return the backend data. What's frustrating here is that this was working correctly the last time I worked on it and can't find what I could have possibly changed to break it.
javascript jquery json reactjs
7
That suggests that your "JSON" is actually HTML. Look at the data you are getting back from the server.
– Quentin
May 17 '16 at 15:22
1
This is the error you get if you do something likeJSON.parse("<foo>")
-- a JSON string (which you expect withdataType: 'json'
) cannot begin with<
.
– apsillers
May 17 '16 at 15:25
As @quantin said, it can be html, maybe error of some sort, try the same url with some rest clients
– maurycy
May 17 '16 at 15:25
like I mentioned, i tried it with an empty db (which returns simply ) and it still gives the same error
– Cameron Sima
May 17 '16 at 15:26
You most likely need to proxy API requests depending on yourNODE_ENV
. See this: github.com/facebookincubator/create-react-app/blob/master/…
– Kevin Suttle
Dec 21 '16 at 16:35
|
show 1 more comment
In a React app component which handles Facebook-like content feeds, I am running into an error:
Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0
I ran into a similar error which turned out to be a typo in the HTML within the render function, but that doesn't seem to be the case here.
More confusingly, I rolled the code back to an earlier, known-working version and I'm still getting the error.
Feed.js:
import React from 'react';
var ThreadForm = React.createClass({
getInitialState: function () {
return {author: '',
text: '',
included: '',
victim: ''
}
},
handleAuthorChange: function (e) {
this.setState({author: e.target.value})
},
handleTextChange: function (e) {
this.setState({text: e.target.value})
},
handleIncludedChange: function (e) {
this.setState({included: e.target.value})
},
handleVictimChange: function (e) {
this.setState({victim: e.target.value})
},
handleSubmit: function (e) {
e.preventDefault()
var author = this.state.author.trim()
var text = this.state.text.trim()
var included = this.state.included.trim()
var victim = this.state.victim.trim()
if (!text || !author || !included || !victim) {
return
}
this.props.onThreadSubmit({author: author,
text: text,
included: included,
victim: victim
})
this.setState({author: '',
text: '',
included: '',
victim: ''
})
},
render: function () {
return (
<form className="threadForm" onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Your name"
value={this.state.author}
onChange={this.handleAuthorChange} />
<input
type="text"
placeholder="Say something..."
value={this.state.text}
onChange={this.handleTextChange} />
<input
type="text"
placeholder="Name your victim"
value={this.state.victim}
onChange={this.handleVictimChange} />
<input
type="text"
placeholder="Who can see?"
value={this.state.included}
onChange={this.handleIncludedChange} />
<input type="submit" value="Post" />
</form>
)
}
})
var ThreadsBox = React.createClass({
loadThreadsFromServer: function () {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function (data) {
this.setState({data: data})
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString())
}.bind(this)
})
},
handleThreadSubmit: function (thread) {
var threads = this.state.data
var newThreads = threads.concat([thread])
this.setState({data: newThreads})
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: thread,
success: function (data) {
this.setState({data: data})
}.bind(this),
error: function (xhr, status, err) {
this.setState({data: threads})
console.error(this.props.url, status, err.toString())
}.bind(this)
})
},
getInitialState: function () {
return {data: }
},
componentDidMount: function () {
this.loadThreadsFromServer()
setInterval(this.loadThreadsFromServer, this.props.pollInterval)
},
render: function () {
return (
<div className="threadsBox">
<h1>Feed</h1>
<div>
<ThreadForm onThreadSubmit={this.handleThreadSubmit} />
</div>
</div>
)
}
})
module.exports = ThreadsBox
In Chrome developer tools, the error seems to be coming from this function:
loadThreadsFromServer: function loadThreadsFromServer() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function (data) {
this.setState({ data: data });
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
with the line console.error(this.props.url, status, err.toString()
underlined.
Since it looks like the error seems to have something to do with pulling JSON data from the server, I tried starting from a blank db, but the error persists. The error seems to be called in an infinite loop presumably as React continuously tries to connect to the server and eventually crashes the browser.
EDIT:
I've checked the server response with Chrome dev tools and Chrome REST client, and the data appears to be proper JSON.
EDIT 2:
It appears that though the intended API endpoint is indeed returning the correct JSON data and format, React is polling http://localhost:3000/?_=1463499798727
instead of the expected http://localhost:3001/api/threads
.
I am running a webpack hot-reload server on port 3000 with the express app running on port 3001 to return the backend data. What's frustrating here is that this was working correctly the last time I worked on it and can't find what I could have possibly changed to break it.
javascript jquery json reactjs
In a React app component which handles Facebook-like content feeds, I am running into an error:
Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0
I ran into a similar error which turned out to be a typo in the HTML within the render function, but that doesn't seem to be the case here.
More confusingly, I rolled the code back to an earlier, known-working version and I'm still getting the error.
Feed.js:
import React from 'react';
var ThreadForm = React.createClass({
getInitialState: function () {
return {author: '',
text: '',
included: '',
victim: ''
}
},
handleAuthorChange: function (e) {
this.setState({author: e.target.value})
},
handleTextChange: function (e) {
this.setState({text: e.target.value})
},
handleIncludedChange: function (e) {
this.setState({included: e.target.value})
},
handleVictimChange: function (e) {
this.setState({victim: e.target.value})
},
handleSubmit: function (e) {
e.preventDefault()
var author = this.state.author.trim()
var text = this.state.text.trim()
var included = this.state.included.trim()
var victim = this.state.victim.trim()
if (!text || !author || !included || !victim) {
return
}
this.props.onThreadSubmit({author: author,
text: text,
included: included,
victim: victim
})
this.setState({author: '',
text: '',
included: '',
victim: ''
})
},
render: function () {
return (
<form className="threadForm" onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Your name"
value={this.state.author}
onChange={this.handleAuthorChange} />
<input
type="text"
placeholder="Say something..."
value={this.state.text}
onChange={this.handleTextChange} />
<input
type="text"
placeholder="Name your victim"
value={this.state.victim}
onChange={this.handleVictimChange} />
<input
type="text"
placeholder="Who can see?"
value={this.state.included}
onChange={this.handleIncludedChange} />
<input type="submit" value="Post" />
</form>
)
}
})
var ThreadsBox = React.createClass({
loadThreadsFromServer: function () {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function (data) {
this.setState({data: data})
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString())
}.bind(this)
})
},
handleThreadSubmit: function (thread) {
var threads = this.state.data
var newThreads = threads.concat([thread])
this.setState({data: newThreads})
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: thread,
success: function (data) {
this.setState({data: data})
}.bind(this),
error: function (xhr, status, err) {
this.setState({data: threads})
console.error(this.props.url, status, err.toString())
}.bind(this)
})
},
getInitialState: function () {
return {data: }
},
componentDidMount: function () {
this.loadThreadsFromServer()
setInterval(this.loadThreadsFromServer, this.props.pollInterval)
},
render: function () {
return (
<div className="threadsBox">
<h1>Feed</h1>
<div>
<ThreadForm onThreadSubmit={this.handleThreadSubmit} />
</div>
</div>
)
}
})
module.exports = ThreadsBox
In Chrome developer tools, the error seems to be coming from this function:
loadThreadsFromServer: function loadThreadsFromServer() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function (data) {
this.setState({ data: data });
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
with the line console.error(this.props.url, status, err.toString()
underlined.
Since it looks like the error seems to have something to do with pulling JSON data from the server, I tried starting from a blank db, but the error persists. The error seems to be called in an infinite loop presumably as React continuously tries to connect to the server and eventually crashes the browser.
EDIT:
I've checked the server response with Chrome dev tools and Chrome REST client, and the data appears to be proper JSON.
EDIT 2:
It appears that though the intended API endpoint is indeed returning the correct JSON data and format, React is polling http://localhost:3000/?_=1463499798727
instead of the expected http://localhost:3001/api/threads
.
I am running a webpack hot-reload server on port 3000 with the express app running on port 3001 to return the backend data. What's frustrating here is that this was working correctly the last time I worked on it and can't find what I could have possibly changed to break it.
javascript jquery json reactjs
javascript jquery json reactjs
edited Dec 18 '18 at 18:27
miken32
24.1k95073
24.1k95073
asked May 17 '16 at 15:21
Cameron SimaCameron Sima
1,16641432
1,16641432
7
That suggests that your "JSON" is actually HTML. Look at the data you are getting back from the server.
– Quentin
May 17 '16 at 15:22
1
This is the error you get if you do something likeJSON.parse("<foo>")
-- a JSON string (which you expect withdataType: 'json'
) cannot begin with<
.
– apsillers
May 17 '16 at 15:25
As @quantin said, it can be html, maybe error of some sort, try the same url with some rest clients
– maurycy
May 17 '16 at 15:25
like I mentioned, i tried it with an empty db (which returns simply ) and it still gives the same error
– Cameron Sima
May 17 '16 at 15:26
You most likely need to proxy API requests depending on yourNODE_ENV
. See this: github.com/facebookincubator/create-react-app/blob/master/…
– Kevin Suttle
Dec 21 '16 at 16:35
|
show 1 more comment
7
That suggests that your "JSON" is actually HTML. Look at the data you are getting back from the server.
– Quentin
May 17 '16 at 15:22
1
This is the error you get if you do something likeJSON.parse("<foo>")
-- a JSON string (which you expect withdataType: 'json'
) cannot begin with<
.
– apsillers
May 17 '16 at 15:25
As @quantin said, it can be html, maybe error of some sort, try the same url with some rest clients
– maurycy
May 17 '16 at 15:25
like I mentioned, i tried it with an empty db (which returns simply ) and it still gives the same error
– Cameron Sima
May 17 '16 at 15:26
You most likely need to proxy API requests depending on yourNODE_ENV
. See this: github.com/facebookincubator/create-react-app/blob/master/…
– Kevin Suttle
Dec 21 '16 at 16:35
7
7
That suggests that your "JSON" is actually HTML. Look at the data you are getting back from the server.
– Quentin
May 17 '16 at 15:22
That suggests that your "JSON" is actually HTML. Look at the data you are getting back from the server.
– Quentin
May 17 '16 at 15:22
1
1
This is the error you get if you do something like
JSON.parse("<foo>")
-- a JSON string (which you expect with dataType: 'json'
) cannot begin with <
.– apsillers
May 17 '16 at 15:25
This is the error you get if you do something like
JSON.parse("<foo>")
-- a JSON string (which you expect with dataType: 'json'
) cannot begin with <
.– apsillers
May 17 '16 at 15:25
As @quantin said, it can be html, maybe error of some sort, try the same url with some rest clients
– maurycy
May 17 '16 at 15:25
As @quantin said, it can be html, maybe error of some sort, try the same url with some rest clients
– maurycy
May 17 '16 at 15:25
like I mentioned, i tried it with an empty db (which returns simply ) and it still gives the same error
– Cameron Sima
May 17 '16 at 15:26
like I mentioned, i tried it with an empty db (which returns simply ) and it still gives the same error
– Cameron Sima
May 17 '16 at 15:26
You most likely need to proxy API requests depending on your
NODE_ENV
. See this: github.com/facebookincubator/create-react-app/blob/master/…– Kevin Suttle
Dec 21 '16 at 16:35
You most likely need to proxy API requests depending on your
NODE_ENV
. See this: github.com/facebookincubator/create-react-app/blob/master/…– Kevin Suttle
Dec 21 '16 at 16:35
|
show 1 more comment
22 Answers
22
active
oldest
votes
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.
3
Thanks, I did this and you're right -- react is polling the wrong url and is returning the contents of index.html. I just can't find out why.
– Cameron Sima
May 17 '16 at 15:49
5
Thanks for the additional debugging statement, although I needed to useconsole.warn(jqxhr.responseText)
. That was very helpful in diagnosing my problem.
– user2441511
Aug 31 '16 at 19:50
@Mimi314159,console.log
,console.warn
andconsole.error
will all write to your Console. However, the Console will usually provide Logging Filter options, so be sure that those are enabled or disabled as you prefer.
– George Bailey
Aug 31 '16 at 20:48
1
In my case, a PHP error was occuring which caused the server to return HTML rather than valid JSON.
– Derek S
Sep 5 '17 at 20:54
add a comment |
You're receiving HTML (or XML) back from the server, but the dataType: json
is telling jQuery to parse as JSON. Check the "Network" tab in Chrome dev tools to see contents of the server's response.
I checked, and it appears to be returning properly formatted json. Here's the response header: Access-Control-Allow-Origin:* Cache-Control:no-cache Content-Length:2487 Content-Type:application/json; charset=utf-8 Date:Tue, 17 May 2016 15:34:00 GMT ETag:W/"9b7-yi1/G0RRpr0DlOVc9u7cMw" X-Powered-By:Express
– Cameron Sima
May 17 '16 at 15:36
that's a great tip, thanks
– Biskrem Muhammad
Feb 16 '18 at 18:50
1
so what do we have to do to correct that?
– AVI
Apr 19 '18 at 13:43
1
@AVI I believe you have to specify the MIME type in your resource class. (e.g)@Produces(MediaType.APPLICATION_JSON)
– DJ2
Apr 23 '18 at 19:32
add a comment |
This ended up being a permissions problem for me. I was trying to access a url I didn't have authorization for with cancan, so the url was switched to users/sign_in
. the redirected url responds to html, not json. The first character in a html response is <
.
and when you receive a HTML as response.. how can you redirect to this html? Thank you.
– JuMoGar
May 24 '17 at 22:06
1
I had the same, although in ASP.NET MVC. For other .NETters, I had forgotten to decorate my action with the [AllowAnonymous] attribute so the framework was trying to return me the unauthorized error in HTML which was crashing my AJAX call.
– Jason Marsell
Nov 3 '17 at 20:26
add a comment |
In my case, I was getting this running webpack, and it turned out to be some corruption somewhere in the local node_modules dir.
rm -rf node_modules
npm install
...was enough to get it working right again.
didnt help still with the same error
– HKI345
Feb 1 at 9:22
add a comment |
I experienced this error "SyntaxError: Unexpected token m in JSON at position", where the token 'm' can be any other characters.
It turned out that I missed one of the double quotes in the JSON object when I was using RESTconsole for DB test, as {"name: "math"}, the correct one should be {"name": "math"}
It took me a lot effort to figure out this clumsy mistake. I am afraid others would run into similar bummers.
add a comment |
I my case the error was a result of me not assigning my return value to a variable. The following caused the error message:
return new JavaScriptSerializer().Serialize("hello");
I changed it to:
string H = "hello";
return new JavaScriptSerializer().Serialize(H);
Without the variable JSON is unable to properly format the data.
add a comment |
I had the same error message following a tutorial. Our issue seems to be 'url: this.props.url' in the ajax call. In React.DOM when you are creating your element, mine looks like this.
ReactDOM.render(
<CommentBox data="/api/comments" pollInterval={2000}/>,
document.getElementById('content')
);
Well, this CommentBox does not have a url in its props, just data. When I switched url: this.props.url
-> url: this.props.data
, it made the right call to the server and I got back the expected data.
I hope it helps.
add a comment |
My problem was that I was getting the data back in a string
which was not in a proper JSON format, which I was then trying to parse it. simple example: JSON.parse('{hello there}')
will give an error at h. In my case the callback url was returning an unnecessary character before the objects: employee_names([{"name":....
and was getting error at e at 0. My callback URL itself had an issue which when fixed, returned only objects.
add a comment |
This error occurs when you define the response as application/json
and you are getting a HTML as a response. Basically, this happened when you are writing server side script for specific url with a response of JSON but the error format is in HTML.
add a comment |
In my case, for an Azure hosted Angular 2/4 site, my API call to mySite/api/... was redirecting due to mySite routing issues. So, it was returning the HTML from the redirected page instead of the api JSON. I added an exclusion in a web.config file for the api path.
I was not getting this error when developing locally because the Site and API were on different ports. There is probably a better way to do this ... but it worked.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<clear />
<!-- ignore static files -->
<rule name="AngularJS Conditions" stopProcessing="true">
<match url="(app/.*|css/.*|fonts/.*|assets/.*|images/.*|js/.*|api/.*)" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
<action type="None" />
</rule>
<!--remaining all other url's point to index.html file -->
<rule name="AngularJS Wildcard" enabled="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
<action type="Rewrite" url="index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
add a comment |
This might be old. But, it just occurred in angular, the content type for request and response were different in my code. So, check headers for ,
let headers = new Headers({
'Content-Type': 'application/json',
**Accept**: 'application/json'
});
in React axios
axios({
method:'get',
url:'http:// ',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
responseType:'json'
})
jQuery Ajax:
$.ajax({
url: this.props.url,
dataType: 'json',
**headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},**
cache: false,
success: function (data) {
this.setState({ data: data });
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
add a comment |
After spending a lot of time with this, I found out that in my case the problem was having "homepage" defined on my package.json file made my app not work on firebase (same 'token' error).
I created my react app using create-react-app, then I used the firebase guide on the READ.me file to deploy to github pages, realized I had to do extra work for the router to work, and switched to firebase. github guide had added the homepage key on package.json and caused the deploy issue.
add a comment |
Protip: Testing json on a local Node.js server? Make sure you don't already have something routing to that path
'/:url(app|assets|stuff|etc)';
add a comment |
On a general level this error occurs when a JSON object is parsed that has syntax errors in it. Think of something like this, where the message property contains unescaped double quotes:
{
"data": [{
"code": "1",
"message": "This message has "unescaped" quotes, which is a JSON syntax error."
}]
}
If you have JSON in your app somewhere then it's good to run it through JSONLint to verify that it doesn't have a syntax error. Usually this isn't the case though in my experience, it's usually JSON returned from an API that's the culprit.
When an XHR request is made to an HTTP API that returns a response with a Content-Type:application/json; charset=UTF-8
header which contains invalid JSON in the response body you'll see this error.
If a server-side API controller is improperly handling a syntax error, and it's being printed out as part of the response, that will break the structure of JSON returned. A good example of this would be an API response containing a PHP Warning or Notice in the response body:
<b>Notice</b>: Undefined variable: something in <b>/path/to/some-api-controller.php</b> on line <b>99</b><br />
{
"success": false,
"data": [{ ... }]
}
95% of the time this is the source of the issue for me, and though it's somewhat addressed here in the other responses I didn't feel it was clearly described. Hopefully this helps, if you're looking for a handy way to track down which API response contains a JSON syntax error I've written an Angular module for that.
Here's the module:
/**
* Track Incomplete XHR Requests
*
* Extend httpInterceptor to track XHR completions and keep a queue
* of our HTTP requests in order to find if any are incomplete or
* never finish, usually this is the source of the issue if it's
* XHR related
*/
angular.module( "xhrErrorTracking", [
'ng',
'ngResource'
] )
.factory( 'xhrErrorTracking', [ '$q', function( $q ) {
var currentResponse = false;
return {
response: function( response ) {
currentResponse = response;
return response || $q.when( response );
},
responseError: function( rejection ) {
var requestDesc = currentResponse.config.method + ' ' + currentResponse.config.url;
if ( currentResponse.config.params ) requestDesc += ' ' + JSON.stringify( currentResponse.config.params );
console.warn( 'JSON Errors Found in XHR Response: ' + requestDesc, currentResponse );
return $q.reject( rejection );
}
};
} ] )
.config( [ '$httpProvider', function( $httpProvider ) {
$httpProvider.interceptors.push( 'xhrErrorTracking' );
} ] );
More details can be found in the blog article referenced above, I haven't posted everything found there here as it's probably not all relevant.
add a comment |
For me, this happened when one of the properties on the object I was returning as JSON threw an exception.
public Dictionary<string, int> Clients { get; set; }
public int CRCount
{
get
{
var count = 0;
//throws when Clients is null
foreach (var c in Clients) {
count += c.Value;
}
return count;
}
}
Adding a null check, fixed it for me:
public Dictionary<string, int> Clients { get; set; }
public int CRCount
{
get
{
var count = 0;
if (Clients != null) {
foreach (var c in Clients) {
count += c.Value;
}
}
return count;
}
}
add a comment |
just something basic to check, make sure you dont have anything commented out in the json file
//comments here will not be parsed and throw error
add a comment |
Just to add to the answers, it also happens when your API response includes
<?php{username: 'Some'}
which could be a case when your backend is using PHP.
add a comment |
In python you can use json.Dump(str) before send result to html template.
with this command string convert to correct json format and send to html template. After send this result to JSON.parse(result) , this is correct response and you can use this.
add a comment |
For some, this may help you guys:
I had a similar experience with Wordpress REST API. I even used Postman to check if I had the correct routes or endpoint. I later found out that I accidentally put an "echo" inside my script - hooks:
Debug & check your console
Cause of the error
So basically, this means that I printed a value that isn't JSON that is mixed with the script that causes AJAX error - "SyntaxError: Unexpected token r in JSON at position 0"
add a comment |
This might cause due to your javascript code is looking at some json response and you received something else like text.
1
Please elaborate while giving answers rather than giving one liners, unless they outright solve answers. The explanation would help the answer-seekers understand the solution better.
– Rai
Nov 26 '18 at 11:41
add a comment |
I was having same problem. I am using a simple node.js server to send response to a client made in Angular 7. Initially I was sending response.end('Hello world from nodejs server');
to client but somehow angular was unable to parse it.
add a comment |
Unexpected token < in JSON at position 0
A simple solution to this error is to write a comment in styles.less
file.
38
This is one of the most bizarre answers I've ever seen on Stackoverflow.
– Kevin Leary
Jul 7 '17 at 17:17
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37280274%2fsyntaxerror-unexpected-token-in-json-at-position-0%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
22 Answers
22
active
oldest
votes
22 Answers
22
active
oldest
votes
active
oldest
votes
active
oldest
votes
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.
3
Thanks, I did this and you're right -- react is polling the wrong url and is returning the contents of index.html. I just can't find out why.
– Cameron Sima
May 17 '16 at 15:49
5
Thanks for the additional debugging statement, although I needed to useconsole.warn(jqxhr.responseText)
. That was very helpful in diagnosing my problem.
– user2441511
Aug 31 '16 at 19:50
@Mimi314159,console.log
,console.warn
andconsole.error
will all write to your Console. However, the Console will usually provide Logging Filter options, so be sure that those are enabled or disabled as you prefer.
– George Bailey
Aug 31 '16 at 20:48
1
In my case, a PHP error was occuring which caused the server to return HTML rather than valid JSON.
– Derek S
Sep 5 '17 at 20:54
add a comment |
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.
3
Thanks, I did this and you're right -- react is polling the wrong url and is returning the contents of index.html. I just can't find out why.
– Cameron Sima
May 17 '16 at 15:49
5
Thanks for the additional debugging statement, although I needed to useconsole.warn(jqxhr.responseText)
. That was very helpful in diagnosing my problem.
– user2441511
Aug 31 '16 at 19:50
@Mimi314159,console.log
,console.warn
andconsole.error
will all write to your Console. However, the Console will usually provide Logging Filter options, so be sure that those are enabled or disabled as you prefer.
– George Bailey
Aug 31 '16 at 20:48
1
In my case, a PHP error was occuring which caused the server to return HTML rather than valid JSON.
– Derek S
Sep 5 '17 at 20:54
add a comment |
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.
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.
edited May 17 '16 at 15:49
answered May 17 '16 at 15:47
George BaileyGeorge Bailey
37.4k67195306
37.4k67195306
3
Thanks, I did this and you're right -- react is polling the wrong url and is returning the contents of index.html. I just can't find out why.
– Cameron Sima
May 17 '16 at 15:49
5
Thanks for the additional debugging statement, although I needed to useconsole.warn(jqxhr.responseText)
. That was very helpful in diagnosing my problem.
– user2441511
Aug 31 '16 at 19:50
@Mimi314159,console.log
,console.warn
andconsole.error
will all write to your Console. However, the Console will usually provide Logging Filter options, so be sure that those are enabled or disabled as you prefer.
– George Bailey
Aug 31 '16 at 20:48
1
In my case, a PHP error was occuring which caused the server to return HTML rather than valid JSON.
– Derek S
Sep 5 '17 at 20:54
add a comment |
3
Thanks, I did this and you're right -- react is polling the wrong url and is returning the contents of index.html. I just can't find out why.
– Cameron Sima
May 17 '16 at 15:49
5
Thanks for the additional debugging statement, although I needed to useconsole.warn(jqxhr.responseText)
. That was very helpful in diagnosing my problem.
– user2441511
Aug 31 '16 at 19:50
@Mimi314159,console.log
,console.warn
andconsole.error
will all write to your Console. However, the Console will usually provide Logging Filter options, so be sure that those are enabled or disabled as you prefer.
– George Bailey
Aug 31 '16 at 20:48
1
In my case, a PHP error was occuring which caused the server to return HTML rather than valid JSON.
– Derek S
Sep 5 '17 at 20:54
3
3
Thanks, I did this and you're right -- react is polling the wrong url and is returning the contents of index.html. I just can't find out why.
– Cameron Sima
May 17 '16 at 15:49
Thanks, I did this and you're right -- react is polling the wrong url and is returning the contents of index.html. I just can't find out why.
– Cameron Sima
May 17 '16 at 15:49
5
5
Thanks for the additional debugging statement, although I needed to use
console.warn(jqxhr.responseText)
. That was very helpful in diagnosing my problem.– user2441511
Aug 31 '16 at 19:50
Thanks for the additional debugging statement, although I needed to use
console.warn(jqxhr.responseText)
. That was very helpful in diagnosing my problem.– user2441511
Aug 31 '16 at 19:50
@Mimi314159,
console.log
, console.warn
and console.error
will all write to your Console. However, the Console will usually provide Logging Filter options, so be sure that those are enabled or disabled as you prefer.– George Bailey
Aug 31 '16 at 20:48
@Mimi314159,
console.log
, console.warn
and console.error
will all write to your Console. However, the Console will usually provide Logging Filter options, so be sure that those are enabled or disabled as you prefer.– George Bailey
Aug 31 '16 at 20:48
1
1
In my case, a PHP error was occuring which caused the server to return HTML rather than valid JSON.
– Derek S
Sep 5 '17 at 20:54
In my case, a PHP error was occuring which caused the server to return HTML rather than valid JSON.
– Derek S
Sep 5 '17 at 20:54
add a comment |
You're receiving HTML (or XML) back from the server, but the dataType: json
is telling jQuery to parse as JSON. Check the "Network" tab in Chrome dev tools to see contents of the server's response.
I checked, and it appears to be returning properly formatted json. Here's the response header: Access-Control-Allow-Origin:* Cache-Control:no-cache Content-Length:2487 Content-Type:application/json; charset=utf-8 Date:Tue, 17 May 2016 15:34:00 GMT ETag:W/"9b7-yi1/G0RRpr0DlOVc9u7cMw" X-Powered-By:Express
– Cameron Sima
May 17 '16 at 15:36
that's a great tip, thanks
– Biskrem Muhammad
Feb 16 '18 at 18:50
1
so what do we have to do to correct that?
– AVI
Apr 19 '18 at 13:43
1
@AVI I believe you have to specify the MIME type in your resource class. (e.g)@Produces(MediaType.APPLICATION_JSON)
– DJ2
Apr 23 '18 at 19:32
add a comment |
You're receiving HTML (or XML) back from the server, but the dataType: json
is telling jQuery to parse as JSON. Check the "Network" tab in Chrome dev tools to see contents of the server's response.
I checked, and it appears to be returning properly formatted json. Here's the response header: Access-Control-Allow-Origin:* Cache-Control:no-cache Content-Length:2487 Content-Type:application/json; charset=utf-8 Date:Tue, 17 May 2016 15:34:00 GMT ETag:W/"9b7-yi1/G0RRpr0DlOVc9u7cMw" X-Powered-By:Express
– Cameron Sima
May 17 '16 at 15:36
that's a great tip, thanks
– Biskrem Muhammad
Feb 16 '18 at 18:50
1
so what do we have to do to correct that?
– AVI
Apr 19 '18 at 13:43
1
@AVI I believe you have to specify the MIME type in your resource class. (e.g)@Produces(MediaType.APPLICATION_JSON)
– DJ2
Apr 23 '18 at 19:32
add a comment |
You're receiving HTML (or XML) back from the server, but the dataType: json
is telling jQuery to parse as JSON. Check the "Network" tab in Chrome dev tools to see contents of the server's response.
You're receiving HTML (or XML) back from the server, but the dataType: json
is telling jQuery to parse as JSON. Check the "Network" tab in Chrome dev tools to see contents of the server's response.
answered May 17 '16 at 15:29
nilnil
498512
498512
I checked, and it appears to be returning properly formatted json. Here's the response header: Access-Control-Allow-Origin:* Cache-Control:no-cache Content-Length:2487 Content-Type:application/json; charset=utf-8 Date:Tue, 17 May 2016 15:34:00 GMT ETag:W/"9b7-yi1/G0RRpr0DlOVc9u7cMw" X-Powered-By:Express
– Cameron Sima
May 17 '16 at 15:36
that's a great tip, thanks
– Biskrem Muhammad
Feb 16 '18 at 18:50
1
so what do we have to do to correct that?
– AVI
Apr 19 '18 at 13:43
1
@AVI I believe you have to specify the MIME type in your resource class. (e.g)@Produces(MediaType.APPLICATION_JSON)
– DJ2
Apr 23 '18 at 19:32
add a comment |
I checked, and it appears to be returning properly formatted json. Here's the response header: Access-Control-Allow-Origin:* Cache-Control:no-cache Content-Length:2487 Content-Type:application/json; charset=utf-8 Date:Tue, 17 May 2016 15:34:00 GMT ETag:W/"9b7-yi1/G0RRpr0DlOVc9u7cMw" X-Powered-By:Express
– Cameron Sima
May 17 '16 at 15:36
that's a great tip, thanks
– Biskrem Muhammad
Feb 16 '18 at 18:50
1
so what do we have to do to correct that?
– AVI
Apr 19 '18 at 13:43
1
@AVI I believe you have to specify the MIME type in your resource class. (e.g)@Produces(MediaType.APPLICATION_JSON)
– DJ2
Apr 23 '18 at 19:32
I checked, and it appears to be returning properly formatted json. Here's the response header: Access-Control-Allow-Origin:* Cache-Control:no-cache Content-Length:2487 Content-Type:application/json; charset=utf-8 Date:Tue, 17 May 2016 15:34:00 GMT ETag:W/"9b7-yi1/G0RRpr0DlOVc9u7cMw" X-Powered-By:Express
– Cameron Sima
May 17 '16 at 15:36
I checked, and it appears to be returning properly formatted json. Here's the response header: Access-Control-Allow-Origin:* Cache-Control:no-cache Content-Length:2487 Content-Type:application/json; charset=utf-8 Date:Tue, 17 May 2016 15:34:00 GMT ETag:W/"9b7-yi1/G0RRpr0DlOVc9u7cMw" X-Powered-By:Express
– Cameron Sima
May 17 '16 at 15:36
that's a great tip, thanks
– Biskrem Muhammad
Feb 16 '18 at 18:50
that's a great tip, thanks
– Biskrem Muhammad
Feb 16 '18 at 18:50
1
1
so what do we have to do to correct that?
– AVI
Apr 19 '18 at 13:43
so what do we have to do to correct that?
– AVI
Apr 19 '18 at 13:43
1
1
@AVI I believe you have to specify the MIME type in your resource class. (e.g)
@Produces(MediaType.APPLICATION_JSON)
– DJ2
Apr 23 '18 at 19:32
@AVI I believe you have to specify the MIME type in your resource class. (e.g)
@Produces(MediaType.APPLICATION_JSON)
– DJ2
Apr 23 '18 at 19:32
add a comment |
This ended up being a permissions problem for me. I was trying to access a url I didn't have authorization for with cancan, so the url was switched to users/sign_in
. the redirected url responds to html, not json. The first character in a html response is <
.
and when you receive a HTML as response.. how can you redirect to this html? Thank you.
– JuMoGar
May 24 '17 at 22:06
1
I had the same, although in ASP.NET MVC. For other .NETters, I had forgotten to decorate my action with the [AllowAnonymous] attribute so the framework was trying to return me the unauthorized error in HTML which was crashing my AJAX call.
– Jason Marsell
Nov 3 '17 at 20:26
add a comment |
This ended up being a permissions problem for me. I was trying to access a url I didn't have authorization for with cancan, so the url was switched to users/sign_in
. the redirected url responds to html, not json. The first character in a html response is <
.
and when you receive a HTML as response.. how can you redirect to this html? Thank you.
– JuMoGar
May 24 '17 at 22:06
1
I had the same, although in ASP.NET MVC. For other .NETters, I had forgotten to decorate my action with the [AllowAnonymous] attribute so the framework was trying to return me the unauthorized error in HTML which was crashing my AJAX call.
– Jason Marsell
Nov 3 '17 at 20:26
add a comment |
This ended up being a permissions problem for me. I was trying to access a url I didn't have authorization for with cancan, so the url was switched to users/sign_in
. the redirected url responds to html, not json. The first character in a html response is <
.
This ended up being a permissions problem for me. I was trying to access a url I didn't have authorization for with cancan, so the url was switched to users/sign_in
. the redirected url responds to html, not json. The first character in a html response is <
.
answered Sep 16 '16 at 22:51
Andrew ShenstoneAndrew Shenstone
14616
14616
and when you receive a HTML as response.. how can you redirect to this html? Thank you.
– JuMoGar
May 24 '17 at 22:06
1
I had the same, although in ASP.NET MVC. For other .NETters, I had forgotten to decorate my action with the [AllowAnonymous] attribute so the framework was trying to return me the unauthorized error in HTML which was crashing my AJAX call.
– Jason Marsell
Nov 3 '17 at 20:26
add a comment |
and when you receive a HTML as response.. how can you redirect to this html? Thank you.
– JuMoGar
May 24 '17 at 22:06
1
I had the same, although in ASP.NET MVC. For other .NETters, I had forgotten to decorate my action with the [AllowAnonymous] attribute so the framework was trying to return me the unauthorized error in HTML which was crashing my AJAX call.
– Jason Marsell
Nov 3 '17 at 20:26
and when you receive a HTML as response.. how can you redirect to this html? Thank you.
– JuMoGar
May 24 '17 at 22:06
and when you receive a HTML as response.. how can you redirect to this html? Thank you.
– JuMoGar
May 24 '17 at 22:06
1
1
I had the same, although in ASP.NET MVC. For other .NETters, I had forgotten to decorate my action with the [AllowAnonymous] attribute so the framework was trying to return me the unauthorized error in HTML which was crashing my AJAX call.
– Jason Marsell
Nov 3 '17 at 20:26
I had the same, although in ASP.NET MVC. For other .NETters, I had forgotten to decorate my action with the [AllowAnonymous] attribute so the framework was trying to return me the unauthorized error in HTML which was crashing my AJAX call.
– Jason Marsell
Nov 3 '17 at 20:26
add a comment |
In my case, I was getting this running webpack, and it turned out to be some corruption somewhere in the local node_modules dir.
rm -rf node_modules
npm install
...was enough to get it working right again.
didnt help still with the same error
– HKI345
Feb 1 at 9:22
add a comment |
In my case, I was getting this running webpack, and it turned out to be some corruption somewhere in the local node_modules dir.
rm -rf node_modules
npm install
...was enough to get it working right again.
didnt help still with the same error
– HKI345
Feb 1 at 9:22
add a comment |
In my case, I was getting this running webpack, and it turned out to be some corruption somewhere in the local node_modules dir.
rm -rf node_modules
npm install
...was enough to get it working right again.
In my case, I was getting this running webpack, and it turned out to be some corruption somewhere in the local node_modules dir.
rm -rf node_modules
npm install
...was enough to get it working right again.
answered Jan 7 '17 at 12:43
KevKev
8,682116898
8,682116898
didnt help still with the same error
– HKI345
Feb 1 at 9:22
add a comment |
didnt help still with the same error
– HKI345
Feb 1 at 9:22
didnt help still with the same error
– HKI345
Feb 1 at 9:22
didnt help still with the same error
– HKI345
Feb 1 at 9:22
add a comment |
I experienced this error "SyntaxError: Unexpected token m in JSON at position", where the token 'm' can be any other characters.
It turned out that I missed one of the double quotes in the JSON object when I was using RESTconsole for DB test, as {"name: "math"}, the correct one should be {"name": "math"}
It took me a lot effort to figure out this clumsy mistake. I am afraid others would run into similar bummers.
add a comment |
I experienced this error "SyntaxError: Unexpected token m in JSON at position", where the token 'm' can be any other characters.
It turned out that I missed one of the double quotes in the JSON object when I was using RESTconsole for DB test, as {"name: "math"}, the correct one should be {"name": "math"}
It took me a lot effort to figure out this clumsy mistake. I am afraid others would run into similar bummers.
add a comment |
I experienced this error "SyntaxError: Unexpected token m in JSON at position", where the token 'm' can be any other characters.
It turned out that I missed one of the double quotes in the JSON object when I was using RESTconsole for DB test, as {"name: "math"}, the correct one should be {"name": "math"}
It took me a lot effort to figure out this clumsy mistake. I am afraid others would run into similar bummers.
I experienced this error "SyntaxError: Unexpected token m in JSON at position", where the token 'm' can be any other characters.
It turned out that I missed one of the double quotes in the JSON object when I was using RESTconsole for DB test, as {"name: "math"}, the correct one should be {"name": "math"}
It took me a lot effort to figure out this clumsy mistake. I am afraid others would run into similar bummers.
answered Jan 8 '17 at 6:27
VictorLVictorL
30134
30134
add a comment |
add a comment |
I my case the error was a result of me not assigning my return value to a variable. The following caused the error message:
return new JavaScriptSerializer().Serialize("hello");
I changed it to:
string H = "hello";
return new JavaScriptSerializer().Serialize(H);
Without the variable JSON is unable to properly format the data.
add a comment |
I my case the error was a result of me not assigning my return value to a variable. The following caused the error message:
return new JavaScriptSerializer().Serialize("hello");
I changed it to:
string H = "hello";
return new JavaScriptSerializer().Serialize(H);
Without the variable JSON is unable to properly format the data.
add a comment |
I my case the error was a result of me not assigning my return value to a variable. The following caused the error message:
return new JavaScriptSerializer().Serialize("hello");
I changed it to:
string H = "hello";
return new JavaScriptSerializer().Serialize(H);
Without the variable JSON is unable to properly format the data.
I my case the error was a result of me not assigning my return value to a variable. The following caused the error message:
return new JavaScriptSerializer().Serialize("hello");
I changed it to:
string H = "hello";
return new JavaScriptSerializer().Serialize(H);
Without the variable JSON is unable to properly format the data.
answered Oct 27 '16 at 17:06
VersatileVersatile
586513
586513
add a comment |
add a comment |
I had the same error message following a tutorial. Our issue seems to be 'url: this.props.url' in the ajax call. In React.DOM when you are creating your element, mine looks like this.
ReactDOM.render(
<CommentBox data="/api/comments" pollInterval={2000}/>,
document.getElementById('content')
);
Well, this CommentBox does not have a url in its props, just data. When I switched url: this.props.url
-> url: this.props.data
, it made the right call to the server and I got back the expected data.
I hope it helps.
add a comment |
I had the same error message following a tutorial. Our issue seems to be 'url: this.props.url' in the ajax call. In React.DOM when you are creating your element, mine looks like this.
ReactDOM.render(
<CommentBox data="/api/comments" pollInterval={2000}/>,
document.getElementById('content')
);
Well, this CommentBox does not have a url in its props, just data. When I switched url: this.props.url
-> url: this.props.data
, it made the right call to the server and I got back the expected data.
I hope it helps.
add a comment |
I had the same error message following a tutorial. Our issue seems to be 'url: this.props.url' in the ajax call. In React.DOM when you are creating your element, mine looks like this.
ReactDOM.render(
<CommentBox data="/api/comments" pollInterval={2000}/>,
document.getElementById('content')
);
Well, this CommentBox does not have a url in its props, just data. When I switched url: this.props.url
-> url: this.props.data
, it made the right call to the server and I got back the expected data.
I hope it helps.
I had the same error message following a tutorial. Our issue seems to be 'url: this.props.url' in the ajax call. In React.DOM when you are creating your element, mine looks like this.
ReactDOM.render(
<CommentBox data="/api/comments" pollInterval={2000}/>,
document.getElementById('content')
);
Well, this CommentBox does not have a url in its props, just data. When I switched url: this.props.url
-> url: this.props.data
, it made the right call to the server and I got back the expected data.
I hope it helps.
edited Aug 21 '16 at 9:55
Alexey Subach
4,89472144
4,89472144
answered Aug 21 '16 at 8:29
TimeaTimea
112
112
add a comment |
add a comment |
My problem was that I was getting the data back in a string
which was not in a proper JSON format, which I was then trying to parse it. simple example: JSON.parse('{hello there}')
will give an error at h. In my case the callback url was returning an unnecessary character before the objects: employee_names([{"name":....
and was getting error at e at 0. My callback URL itself had an issue which when fixed, returned only objects.
add a comment |
My problem was that I was getting the data back in a string
which was not in a proper JSON format, which I was then trying to parse it. simple example: JSON.parse('{hello there}')
will give an error at h. In my case the callback url was returning an unnecessary character before the objects: employee_names([{"name":....
and was getting error at e at 0. My callback URL itself had an issue which when fixed, returned only objects.
add a comment |
My problem was that I was getting the data back in a string
which was not in a proper JSON format, which I was then trying to parse it. simple example: JSON.parse('{hello there}')
will give an error at h. In my case the callback url was returning an unnecessary character before the objects: employee_names([{"name":....
and was getting error at e at 0. My callback URL itself had an issue which when fixed, returned only objects.
My problem was that I was getting the data back in a string
which was not in a proper JSON format, which I was then trying to parse it. simple example: JSON.parse('{hello there}')
will give an error at h. In my case the callback url was returning an unnecessary character before the objects: employee_names([{"name":....
and was getting error at e at 0. My callback URL itself had an issue which when fixed, returned only objects.
answered Dec 5 '16 at 18:25
DekeDeke
1,40811223
1,40811223
add a comment |
add a comment |
This error occurs when you define the response as application/json
and you are getting a HTML as a response. Basically, this happened when you are writing server side script for specific url with a response of JSON but the error format is in HTML.
add a comment |
This error occurs when you define the response as application/json
and you are getting a HTML as a response. Basically, this happened when you are writing server side script for specific url with a response of JSON but the error format is in HTML.
add a comment |
This error occurs when you define the response as application/json
and you are getting a HTML as a response. Basically, this happened when you are writing server side script for specific url with a response of JSON but the error format is in HTML.
This error occurs when you define the response as application/json
and you are getting a HTML as a response. Basically, this happened when you are writing server side script for specific url with a response of JSON but the error format is in HTML.
answered Jul 31 '17 at 14:21
sriram veeraghantasriram veeraghanta
12914
12914
add a comment |
add a comment |
In my case, for an Azure hosted Angular 2/4 site, my API call to mySite/api/... was redirecting due to mySite routing issues. So, it was returning the HTML from the redirected page instead of the api JSON. I added an exclusion in a web.config file for the api path.
I was not getting this error when developing locally because the Site and API were on different ports. There is probably a better way to do this ... but it worked.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<clear />
<!-- ignore static files -->
<rule name="AngularJS Conditions" stopProcessing="true">
<match url="(app/.*|css/.*|fonts/.*|assets/.*|images/.*|js/.*|api/.*)" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
<action type="None" />
</rule>
<!--remaining all other url's point to index.html file -->
<rule name="AngularJS Wildcard" enabled="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
<action type="Rewrite" url="index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
add a comment |
In my case, for an Azure hosted Angular 2/4 site, my API call to mySite/api/... was redirecting due to mySite routing issues. So, it was returning the HTML from the redirected page instead of the api JSON. I added an exclusion in a web.config file for the api path.
I was not getting this error when developing locally because the Site and API were on different ports. There is probably a better way to do this ... but it worked.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<clear />
<!-- ignore static files -->
<rule name="AngularJS Conditions" stopProcessing="true">
<match url="(app/.*|css/.*|fonts/.*|assets/.*|images/.*|js/.*|api/.*)" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
<action type="None" />
</rule>
<!--remaining all other url's point to index.html file -->
<rule name="AngularJS Wildcard" enabled="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
<action type="Rewrite" url="index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
add a comment |
In my case, for an Azure hosted Angular 2/4 site, my API call to mySite/api/... was redirecting due to mySite routing issues. So, it was returning the HTML from the redirected page instead of the api JSON. I added an exclusion in a web.config file for the api path.
I was not getting this error when developing locally because the Site and API were on different ports. There is probably a better way to do this ... but it worked.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<clear />
<!-- ignore static files -->
<rule name="AngularJS Conditions" stopProcessing="true">
<match url="(app/.*|css/.*|fonts/.*|assets/.*|images/.*|js/.*|api/.*)" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
<action type="None" />
</rule>
<!--remaining all other url's point to index.html file -->
<rule name="AngularJS Wildcard" enabled="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
<action type="Rewrite" url="index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
In my case, for an Azure hosted Angular 2/4 site, my API call to mySite/api/... was redirecting due to mySite routing issues. So, it was returning the HTML from the redirected page instead of the api JSON. I added an exclusion in a web.config file for the api path.
I was not getting this error when developing locally because the Site and API were on different ports. There is probably a better way to do this ... but it worked.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<clear />
<!-- ignore static files -->
<rule name="AngularJS Conditions" stopProcessing="true">
<match url="(app/.*|css/.*|fonts/.*|assets/.*|images/.*|js/.*|api/.*)" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
<action type="None" />
</rule>
<!--remaining all other url's point to index.html file -->
<rule name="AngularJS Wildcard" enabled="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
<action type="Rewrite" url="index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
edited Jan 10 '18 at 22:38
answered Jul 4 '17 at 16:36
DaveDave
6113
6113
add a comment |
add a comment |
This might be old. But, it just occurred in angular, the content type for request and response were different in my code. So, check headers for ,
let headers = new Headers({
'Content-Type': 'application/json',
**Accept**: 'application/json'
});
in React axios
axios({
method:'get',
url:'http:// ',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
responseType:'json'
})
jQuery Ajax:
$.ajax({
url: this.props.url,
dataType: 'json',
**headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},**
cache: false,
success: function (data) {
this.setState({ data: data });
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
add a comment |
This might be old. But, it just occurred in angular, the content type for request and response were different in my code. So, check headers for ,
let headers = new Headers({
'Content-Type': 'application/json',
**Accept**: 'application/json'
});
in React axios
axios({
method:'get',
url:'http:// ',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
responseType:'json'
})
jQuery Ajax:
$.ajax({
url: this.props.url,
dataType: 'json',
**headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},**
cache: false,
success: function (data) {
this.setState({ data: data });
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
add a comment |
This might be old. But, it just occurred in angular, the content type for request and response were different in my code. So, check headers for ,
let headers = new Headers({
'Content-Type': 'application/json',
**Accept**: 'application/json'
});
in React axios
axios({
method:'get',
url:'http:// ',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
responseType:'json'
})
jQuery Ajax:
$.ajax({
url: this.props.url,
dataType: 'json',
**headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},**
cache: false,
success: function (data) {
this.setState({ data: data });
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
This might be old. But, it just occurred in angular, the content type for request and response were different in my code. So, check headers for ,
let headers = new Headers({
'Content-Type': 'application/json',
**Accept**: 'application/json'
});
in React axios
axios({
method:'get',
url:'http:// ',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
responseType:'json'
})
jQuery Ajax:
$.ajax({
url: this.props.url,
dataType: 'json',
**headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},**
cache: false,
success: function (data) {
this.setState({ data: data });
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
edited Feb 9 '18 at 21:42
community wiki
2 revs, 2 users 97%
MPV
add a comment |
add a comment |
After spending a lot of time with this, I found out that in my case the problem was having "homepage" defined on my package.json file made my app not work on firebase (same 'token' error).
I created my react app using create-react-app, then I used the firebase guide on the READ.me file to deploy to github pages, realized I had to do extra work for the router to work, and switched to firebase. github guide had added the homepage key on package.json and caused the deploy issue.
add a comment |
After spending a lot of time with this, I found out that in my case the problem was having "homepage" defined on my package.json file made my app not work on firebase (same 'token' error).
I created my react app using create-react-app, then I used the firebase guide on the READ.me file to deploy to github pages, realized I had to do extra work for the router to work, and switched to firebase. github guide had added the homepage key on package.json and caused the deploy issue.
add a comment |
After spending a lot of time with this, I found out that in my case the problem was having "homepage" defined on my package.json file made my app not work on firebase (same 'token' error).
I created my react app using create-react-app, then I used the firebase guide on the READ.me file to deploy to github pages, realized I had to do extra work for the router to work, and switched to firebase. github guide had added the homepage key on package.json and caused the deploy issue.
After spending a lot of time with this, I found out that in my case the problem was having "homepage" defined on my package.json file made my app not work on firebase (same 'token' error).
I created my react app using create-react-app, then I used the firebase guide on the READ.me file to deploy to github pages, realized I had to do extra work for the router to work, and switched to firebase. github guide had added the homepage key on package.json and caused the deploy issue.
answered Jan 6 '17 at 16:58
Alejandro B.Alejandro B.
2,68512643
2,68512643
add a comment |
add a comment |
Protip: Testing json on a local Node.js server? Make sure you don't already have something routing to that path
'/:url(app|assets|stuff|etc)';
add a comment |
Protip: Testing json on a local Node.js server? Make sure you don't already have something routing to that path
'/:url(app|assets|stuff|etc)';
add a comment |
Protip: Testing json on a local Node.js server? Make sure you don't already have something routing to that path
'/:url(app|assets|stuff|etc)';
Protip: Testing json on a local Node.js server? Make sure you don't already have something routing to that path
'/:url(app|assets|stuff|etc)';
answered Jan 25 '17 at 20:31
dustinthewebdustintheweb
13210
13210
add a comment |
add a comment |
On a general level this error occurs when a JSON object is parsed that has syntax errors in it. Think of something like this, where the message property contains unescaped double quotes:
{
"data": [{
"code": "1",
"message": "This message has "unescaped" quotes, which is a JSON syntax error."
}]
}
If you have JSON in your app somewhere then it's good to run it through JSONLint to verify that it doesn't have a syntax error. Usually this isn't the case though in my experience, it's usually JSON returned from an API that's the culprit.
When an XHR request is made to an HTTP API that returns a response with a Content-Type:application/json; charset=UTF-8
header which contains invalid JSON in the response body you'll see this error.
If a server-side API controller is improperly handling a syntax error, and it's being printed out as part of the response, that will break the structure of JSON returned. A good example of this would be an API response containing a PHP Warning or Notice in the response body:
<b>Notice</b>: Undefined variable: something in <b>/path/to/some-api-controller.php</b> on line <b>99</b><br />
{
"success": false,
"data": [{ ... }]
}
95% of the time this is the source of the issue for me, and though it's somewhat addressed here in the other responses I didn't feel it was clearly described. Hopefully this helps, if you're looking for a handy way to track down which API response contains a JSON syntax error I've written an Angular module for that.
Here's the module:
/**
* Track Incomplete XHR Requests
*
* Extend httpInterceptor to track XHR completions and keep a queue
* of our HTTP requests in order to find if any are incomplete or
* never finish, usually this is the source of the issue if it's
* XHR related
*/
angular.module( "xhrErrorTracking", [
'ng',
'ngResource'
] )
.factory( 'xhrErrorTracking', [ '$q', function( $q ) {
var currentResponse = false;
return {
response: function( response ) {
currentResponse = response;
return response || $q.when( response );
},
responseError: function( rejection ) {
var requestDesc = currentResponse.config.method + ' ' + currentResponse.config.url;
if ( currentResponse.config.params ) requestDesc += ' ' + JSON.stringify( currentResponse.config.params );
console.warn( 'JSON Errors Found in XHR Response: ' + requestDesc, currentResponse );
return $q.reject( rejection );
}
};
} ] )
.config( [ '$httpProvider', function( $httpProvider ) {
$httpProvider.interceptors.push( 'xhrErrorTracking' );
} ] );
More details can be found in the blog article referenced above, I haven't posted everything found there here as it's probably not all relevant.
add a comment |
On a general level this error occurs when a JSON object is parsed that has syntax errors in it. Think of something like this, where the message property contains unescaped double quotes:
{
"data": [{
"code": "1",
"message": "This message has "unescaped" quotes, which is a JSON syntax error."
}]
}
If you have JSON in your app somewhere then it's good to run it through JSONLint to verify that it doesn't have a syntax error. Usually this isn't the case though in my experience, it's usually JSON returned from an API that's the culprit.
When an XHR request is made to an HTTP API that returns a response with a Content-Type:application/json; charset=UTF-8
header which contains invalid JSON in the response body you'll see this error.
If a server-side API controller is improperly handling a syntax error, and it's being printed out as part of the response, that will break the structure of JSON returned. A good example of this would be an API response containing a PHP Warning or Notice in the response body:
<b>Notice</b>: Undefined variable: something in <b>/path/to/some-api-controller.php</b> on line <b>99</b><br />
{
"success": false,
"data": [{ ... }]
}
95% of the time this is the source of the issue for me, and though it's somewhat addressed here in the other responses I didn't feel it was clearly described. Hopefully this helps, if you're looking for a handy way to track down which API response contains a JSON syntax error I've written an Angular module for that.
Here's the module:
/**
* Track Incomplete XHR Requests
*
* Extend httpInterceptor to track XHR completions and keep a queue
* of our HTTP requests in order to find if any are incomplete or
* never finish, usually this is the source of the issue if it's
* XHR related
*/
angular.module( "xhrErrorTracking", [
'ng',
'ngResource'
] )
.factory( 'xhrErrorTracking', [ '$q', function( $q ) {
var currentResponse = false;
return {
response: function( response ) {
currentResponse = response;
return response || $q.when( response );
},
responseError: function( rejection ) {
var requestDesc = currentResponse.config.method + ' ' + currentResponse.config.url;
if ( currentResponse.config.params ) requestDesc += ' ' + JSON.stringify( currentResponse.config.params );
console.warn( 'JSON Errors Found in XHR Response: ' + requestDesc, currentResponse );
return $q.reject( rejection );
}
};
} ] )
.config( [ '$httpProvider', function( $httpProvider ) {
$httpProvider.interceptors.push( 'xhrErrorTracking' );
} ] );
More details can be found in the blog article referenced above, I haven't posted everything found there here as it's probably not all relevant.
add a comment |
On a general level this error occurs when a JSON object is parsed that has syntax errors in it. Think of something like this, where the message property contains unescaped double quotes:
{
"data": [{
"code": "1",
"message": "This message has "unescaped" quotes, which is a JSON syntax error."
}]
}
If you have JSON in your app somewhere then it's good to run it through JSONLint to verify that it doesn't have a syntax error. Usually this isn't the case though in my experience, it's usually JSON returned from an API that's the culprit.
When an XHR request is made to an HTTP API that returns a response with a Content-Type:application/json; charset=UTF-8
header which contains invalid JSON in the response body you'll see this error.
If a server-side API controller is improperly handling a syntax error, and it's being printed out as part of the response, that will break the structure of JSON returned. A good example of this would be an API response containing a PHP Warning or Notice in the response body:
<b>Notice</b>: Undefined variable: something in <b>/path/to/some-api-controller.php</b> on line <b>99</b><br />
{
"success": false,
"data": [{ ... }]
}
95% of the time this is the source of the issue for me, and though it's somewhat addressed here in the other responses I didn't feel it was clearly described. Hopefully this helps, if you're looking for a handy way to track down which API response contains a JSON syntax error I've written an Angular module for that.
Here's the module:
/**
* Track Incomplete XHR Requests
*
* Extend httpInterceptor to track XHR completions and keep a queue
* of our HTTP requests in order to find if any are incomplete or
* never finish, usually this is the source of the issue if it's
* XHR related
*/
angular.module( "xhrErrorTracking", [
'ng',
'ngResource'
] )
.factory( 'xhrErrorTracking', [ '$q', function( $q ) {
var currentResponse = false;
return {
response: function( response ) {
currentResponse = response;
return response || $q.when( response );
},
responseError: function( rejection ) {
var requestDesc = currentResponse.config.method + ' ' + currentResponse.config.url;
if ( currentResponse.config.params ) requestDesc += ' ' + JSON.stringify( currentResponse.config.params );
console.warn( 'JSON Errors Found in XHR Response: ' + requestDesc, currentResponse );
return $q.reject( rejection );
}
};
} ] )
.config( [ '$httpProvider', function( $httpProvider ) {
$httpProvider.interceptors.push( 'xhrErrorTracking' );
} ] );
More details can be found in the blog article referenced above, I haven't posted everything found there here as it's probably not all relevant.
On a general level this error occurs when a JSON object is parsed that has syntax errors in it. Think of something like this, where the message property contains unescaped double quotes:
{
"data": [{
"code": "1",
"message": "This message has "unescaped" quotes, which is a JSON syntax error."
}]
}
If you have JSON in your app somewhere then it's good to run it through JSONLint to verify that it doesn't have a syntax error. Usually this isn't the case though in my experience, it's usually JSON returned from an API that's the culprit.
When an XHR request is made to an HTTP API that returns a response with a Content-Type:application/json; charset=UTF-8
header which contains invalid JSON in the response body you'll see this error.
If a server-side API controller is improperly handling a syntax error, and it's being printed out as part of the response, that will break the structure of JSON returned. A good example of this would be an API response containing a PHP Warning or Notice in the response body:
<b>Notice</b>: Undefined variable: something in <b>/path/to/some-api-controller.php</b> on line <b>99</b><br />
{
"success": false,
"data": [{ ... }]
}
95% of the time this is the source of the issue for me, and though it's somewhat addressed here in the other responses I didn't feel it was clearly described. Hopefully this helps, if you're looking for a handy way to track down which API response contains a JSON syntax error I've written an Angular module for that.
Here's the module:
/**
* Track Incomplete XHR Requests
*
* Extend httpInterceptor to track XHR completions and keep a queue
* of our HTTP requests in order to find if any are incomplete or
* never finish, usually this is the source of the issue if it's
* XHR related
*/
angular.module( "xhrErrorTracking", [
'ng',
'ngResource'
] )
.factory( 'xhrErrorTracking', [ '$q', function( $q ) {
var currentResponse = false;
return {
response: function( response ) {
currentResponse = response;
return response || $q.when( response );
},
responseError: function( rejection ) {
var requestDesc = currentResponse.config.method + ' ' + currentResponse.config.url;
if ( currentResponse.config.params ) requestDesc += ' ' + JSON.stringify( currentResponse.config.params );
console.warn( 'JSON Errors Found in XHR Response: ' + requestDesc, currentResponse );
return $q.reject( rejection );
}
};
} ] )
.config( [ '$httpProvider', function( $httpProvider ) {
$httpProvider.interceptors.push( 'xhrErrorTracking' );
} ] );
More details can be found in the blog article referenced above, I haven't posted everything found there here as it's probably not all relevant.
edited Jul 7 '17 at 20:37
answered Jul 7 '17 at 19:35
Kevin LearyKevin Leary
4,0503039
4,0503039
add a comment |
add a comment |
For me, this happened when one of the properties on the object I was returning as JSON threw an exception.
public Dictionary<string, int> Clients { get; set; }
public int CRCount
{
get
{
var count = 0;
//throws when Clients is null
foreach (var c in Clients) {
count += c.Value;
}
return count;
}
}
Adding a null check, fixed it for me:
public Dictionary<string, int> Clients { get; set; }
public int CRCount
{
get
{
var count = 0;
if (Clients != null) {
foreach (var c in Clients) {
count += c.Value;
}
}
return count;
}
}
add a comment |
For me, this happened when one of the properties on the object I was returning as JSON threw an exception.
public Dictionary<string, int> Clients { get; set; }
public int CRCount
{
get
{
var count = 0;
//throws when Clients is null
foreach (var c in Clients) {
count += c.Value;
}
return count;
}
}
Adding a null check, fixed it for me:
public Dictionary<string, int> Clients { get; set; }
public int CRCount
{
get
{
var count = 0;
if (Clients != null) {
foreach (var c in Clients) {
count += c.Value;
}
}
return count;
}
}
add a comment |
For me, this happened when one of the properties on the object I was returning as JSON threw an exception.
public Dictionary<string, int> Clients { get; set; }
public int CRCount
{
get
{
var count = 0;
//throws when Clients is null
foreach (var c in Clients) {
count += c.Value;
}
return count;
}
}
Adding a null check, fixed it for me:
public Dictionary<string, int> Clients { get; set; }
public int CRCount
{
get
{
var count = 0;
if (Clients != null) {
foreach (var c in Clients) {
count += c.Value;
}
}
return count;
}
}
For me, this happened when one of the properties on the object I was returning as JSON threw an exception.
public Dictionary<string, int> Clients { get; set; }
public int CRCount
{
get
{
var count = 0;
//throws when Clients is null
foreach (var c in Clients) {
count += c.Value;
}
return count;
}
}
Adding a null check, fixed it for me:
public Dictionary<string, int> Clients { get; set; }
public int CRCount
{
get
{
var count = 0;
if (Clients != null) {
foreach (var c in Clients) {
count += c.Value;
}
}
return count;
}
}
answered Oct 27 '17 at 16:59
WindowWindow
5251515
5251515
add a comment |
add a comment |
just something basic to check, make sure you dont have anything commented out in the json file
//comments here will not be parsed and throw error
add a comment |
just something basic to check, make sure you dont have anything commented out in the json file
//comments here will not be parsed and throw error
add a comment |
just something basic to check, make sure you dont have anything commented out in the json file
//comments here will not be parsed and throw error
just something basic to check, make sure you dont have anything commented out in the json file
//comments here will not be parsed and throw error
answered Nov 27 '17 at 15:42
Akin HwanAkin Hwan
197216
197216
add a comment |
add a comment |
Just to add to the answers, it also happens when your API response includes
<?php{username: 'Some'}
which could be a case when your backend is using PHP.
add a comment |
Just to add to the answers, it also happens when your API response includes
<?php{username: 'Some'}
which could be a case when your backend is using PHP.
add a comment |
Just to add to the answers, it also happens when your API response includes
<?php{username: 'Some'}
which could be a case when your backend is using PHP.
Just to add to the answers, it also happens when your API response includes
<?php{username: 'Some'}
which could be a case when your backend is using PHP.
edited Dec 7 '17 at 1:26
Pang
6,9631664104
6,9631664104
answered May 24 '17 at 11:41
Tushar SharmaTushar Sharma
5110
5110
add a comment |
add a comment |
In python you can use json.Dump(str) before send result to html template.
with this command string convert to correct json format and send to html template. After send this result to JSON.parse(result) , this is correct response and you can use this.
add a comment |
In python you can use json.Dump(str) before send result to html template.
with this command string convert to correct json format and send to html template. After send this result to JSON.parse(result) , this is correct response and you can use this.
add a comment |
In python you can use json.Dump(str) before send result to html template.
with this command string convert to correct json format and send to html template. After send this result to JSON.parse(result) , this is correct response and you can use this.
In python you can use json.Dump(str) before send result to html template.
with this command string convert to correct json format and send to html template. After send this result to JSON.parse(result) , this is correct response and you can use this.
answered Jan 29 '18 at 8:04
user2713125user2713125
85
85
add a comment |
add a comment |
For some, this may help you guys:
I had a similar experience with Wordpress REST API. I even used Postman to check if I had the correct routes or endpoint. I later found out that I accidentally put an "echo" inside my script - hooks:
Debug & check your console
Cause of the error
So basically, this means that I printed a value that isn't JSON that is mixed with the script that causes AJAX error - "SyntaxError: Unexpected token r in JSON at position 0"
add a comment |
For some, this may help you guys:
I had a similar experience with Wordpress REST API. I even used Postman to check if I had the correct routes or endpoint. I later found out that I accidentally put an "echo" inside my script - hooks:
Debug & check your console
Cause of the error
So basically, this means that I printed a value that isn't JSON that is mixed with the script that causes AJAX error - "SyntaxError: Unexpected token r in JSON at position 0"
add a comment |
For some, this may help you guys:
I had a similar experience with Wordpress REST API. I even used Postman to check if I had the correct routes or endpoint. I later found out that I accidentally put an "echo" inside my script - hooks:
Debug & check your console
Cause of the error
So basically, this means that I printed a value that isn't JSON that is mixed with the script that causes AJAX error - "SyntaxError: Unexpected token r in JSON at position 0"
For some, this may help you guys:
I had a similar experience with Wordpress REST API. I even used Postman to check if I had the correct routes or endpoint. I later found out that I accidentally put an "echo" inside my script - hooks:
Debug & check your console
Cause of the error
So basically, this means that I printed a value that isn't JSON that is mixed with the script that causes AJAX error - "SyntaxError: Unexpected token r in JSON at position 0"
answered Sep 28 '18 at 10:37
Ray MaczRay Macz
2818
2818
add a comment |
add a comment |
This might cause due to your javascript code is looking at some json response and you received something else like text.
1
Please elaborate while giving answers rather than giving one liners, unless they outright solve answers. The explanation would help the answer-seekers understand the solution better.
– Rai
Nov 26 '18 at 11:41
add a comment |
This might cause due to your javascript code is looking at some json response and you received something else like text.
1
Please elaborate while giving answers rather than giving one liners, unless they outright solve answers. The explanation would help the answer-seekers understand the solution better.
– Rai
Nov 26 '18 at 11:41
add a comment |
This might cause due to your javascript code is looking at some json response and you received something else like text.
This might cause due to your javascript code is looking at some json response and you received something else like text.
answered Nov 26 '18 at 11:16
R KarwalkarR Karwalkar
1
1
1
Please elaborate while giving answers rather than giving one liners, unless they outright solve answers. The explanation would help the answer-seekers understand the solution better.
– Rai
Nov 26 '18 at 11:41
add a comment |
1
Please elaborate while giving answers rather than giving one liners, unless they outright solve answers. The explanation would help the answer-seekers understand the solution better.
– Rai
Nov 26 '18 at 11:41
1
1
Please elaborate while giving answers rather than giving one liners, unless they outright solve answers. The explanation would help the answer-seekers understand the solution better.
– Rai
Nov 26 '18 at 11:41
Please elaborate while giving answers rather than giving one liners, unless they outright solve answers. The explanation would help the answer-seekers understand the solution better.
– Rai
Nov 26 '18 at 11:41
add a comment |
I was having same problem. I am using a simple node.js server to send response to a client made in Angular 7. Initially I was sending response.end('Hello world from nodejs server');
to client but somehow angular was unable to parse it.
add a comment |
I was having same problem. I am using a simple node.js server to send response to a client made in Angular 7. Initially I was sending response.end('Hello world from nodejs server');
to client but somehow angular was unable to parse it.
add a comment |
I was having same problem. I am using a simple node.js server to send response to a client made in Angular 7. Initially I was sending response.end('Hello world from nodejs server');
to client but somehow angular was unable to parse it.
I was having same problem. I am using a simple node.js server to send response to a client made in Angular 7. Initially I was sending response.end('Hello world from nodejs server');
to client but somehow angular was unable to parse it.
answered Nov 28 '18 at 15:49
MaddyMaddy
59110
59110
add a comment |
add a comment |
Unexpected token < in JSON at position 0
A simple solution to this error is to write a comment in styles.less
file.
38
This is one of the most bizarre answers I've ever seen on Stackoverflow.
– Kevin Leary
Jul 7 '17 at 17:17
add a comment |
Unexpected token < in JSON at position 0
A simple solution to this error is to write a comment in styles.less
file.
38
This is one of the most bizarre answers I've ever seen on Stackoverflow.
– Kevin Leary
Jul 7 '17 at 17:17
add a comment |
Unexpected token < in JSON at position 0
A simple solution to this error is to write a comment in styles.less
file.
Unexpected token < in JSON at position 0
A simple solution to this error is to write a comment in styles.less
file.
edited Mar 5 '17 at 20:10
Tunaki
91.1k22203278
91.1k22203278
answered Mar 5 '17 at 20:03
DaniDani
1
1
38
This is one of the most bizarre answers I've ever seen on Stackoverflow.
– Kevin Leary
Jul 7 '17 at 17:17
add a comment |
38
This is one of the most bizarre answers I've ever seen on Stackoverflow.
– Kevin Leary
Jul 7 '17 at 17:17
38
38
This is one of the most bizarre answers I've ever seen on Stackoverflow.
– Kevin Leary
Jul 7 '17 at 17:17
This is one of the most bizarre answers I've ever seen on Stackoverflow.
– Kevin Leary
Jul 7 '17 at 17:17
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37280274%2fsyntaxerror-unexpected-token-in-json-at-position-0%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
7
That suggests that your "JSON" is actually HTML. Look at the data you are getting back from the server.
– Quentin
May 17 '16 at 15:22
1
This is the error you get if you do something like
JSON.parse("<foo>")
-- a JSON string (which you expect withdataType: 'json'
) cannot begin with<
.– apsillers
May 17 '16 at 15:25
As @quantin said, it can be html, maybe error of some sort, try the same url with some rest clients
– maurycy
May 17 '16 at 15:25
like I mentioned, i tried it with an empty db (which returns simply ) and it still gives the same error
– Cameron Sima
May 17 '16 at 15:26
You most likely need to proxy API requests depending on your
NODE_ENV
. See this: github.com/facebookincubator/create-react-app/blob/master/…– Kevin Suttle
Dec 21 '16 at 16:35