Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 605 Vote(s) - 3.51 Average
  • 1
  • 2
  • 3
  • 4
  • 5
"SyntaxError: Unexpected token < in JSON at position 0"

#1
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.
Reply

#2
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.
Reply

#3
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.
Reply

#4
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.
Reply

#5
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.
Reply

#6
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.
Reply

#7
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)';
Reply

#8
> Unexpected token < in JSON at position 0

A simple solution to this error is to write a comment in `styles.less` file.
Reply

#9
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 see links please register here]

) 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](

[To see links please register here]

).

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.
Reply

#10
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;
}
}
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through