Related
I've been trying to send a GET request to an api to fetch data using Axios but always get a response object with status, headers, config, agents etc and response.data is always empty.
For example, the following code returns me an Axios response object with the hasBody set to true and data being empty.
axios.get(`https://fantasy.premierleague.com/api/leagues-classic/12000/standings/`).then(response => {console.log(response);
console.log(response.data);});
However, when I switched over to using Request library which has been deprecated, I am able to get the response body. For example, the following code works:
request(`https://fantasy.premierleague.com/api/leagues-classic/12000/standings/`, { json: true }, (err, res, body) => {
if (err) { return console.log(err); }
console.log(body);
});
Can someone tell me what am I doing wrong and how can I get the response body using axios? I'm a beginner and have spent hours trying to figure out so I would really appreciate any form of help.
It's not an axios library issue. From what I can tell, the server does't like the user-agents starting with "axios/". Specifying some user agent gives you the expected result:
const axios = require("axios");
axios.get(`https://fantasy.premierleague.com/api/leagues-classic/12000/standings`, {
headers: {
'user-agent': 'not axios',
}
}).then(response => {
console.log(response.data);
});
As for why the requests library works but axios does not: axios is setting the user-agent header to something like axios/0.21.1 or whatever version you have. requests on the other side, leaves the user-agent header unset. It's the server right to handle the request as he pleases.
I have verified the response from this URL https://fantasy.premierleague.com/api/leagues-classic/12000/standings/ - there is no data property in the response
Try like below to read the values:
It seem like your URL at https://fantasy.premierleague.com/api/leagues-classic/12000/standings/ had invalid response body.
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.
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.
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.
SyntaxError: Unexpected token < in JSON at position 0
You are getting an HTML file (or XML) instead of json.
Html files begin with <!DOCTYPE html>.
I "achieved" this error by forgetting the https:// in my fetch method:
fetch(`/api.github.com/users/${login}`)
.then(response => response.json())
.then(setData);
I verified my hunch:
I logged the response as text instead of JSON.
fetch(`/api.github.com/users/${login}`)
.then(response => response.text())
.then(text => console.log(text))
.then(setData);
Yep, an html file.
Solution:
I fixed the error by adding back the https:// in my fetch method.
fetch(`https://api.github.com/users/${login}`)
.then(response => response.json())
.then(setData)
.catch(error => (console.log(error)));
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 <.
In my case, I was getting this running webpack. It turned out to be corrupted somewhere in the local node_modules dir.
rm -rf node_modules
npm install
...was enough to get it working right again.
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 will run into similar issues.
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.
I was facing the same issue.
I removed the dataType:'json' from the $.ajax method.
Those who are using create-react-app and trying to fetch local json files.
As in create-react-app, webpack-dev-server is used to handle the request and for every request it serves the index.html. So you are getting
SyntaxError: Unexpected token < in JSON at position 0.
To solve this, you need to eject the app and modify the webpack-dev-server configuration file.
You can follow the steps from here.
In a nutshell, if you're getting this error or a similar error, that means only one thing: Someplace in our codebase, we were expecting a valid JSON format to process, and we didn't get one. For example,
var string = "some string";
JSON.parse(string)
will throw an error, saying
Uncaught SyntaxError: Unexpected token s in JSON at position 0
Because, the first character in string is s & it's not a valid JSON now. This can throw error in between also. like:
var invalidJSON= '{"foo" : "bar", "missedquotehere : "value" }';
JSON.parse(invalidJSON)
Will throw error:
VM598:1 Uncaught SyntaxError: Unexpected token v in JSON at position 36
because we intentionally missed a quote in the JSON string invalidJSON at position 36.
And if you fix that:
var validJSON= '{"foo" : "bar", "missedquotehere" : "value" }';
JSON.parse(validJSON)
will give you an object in JSON.
This error can be thrown in any place & in any framework/library. Most of the time you may be reading a network response which is not valid JSON. So steps of debugging this issue can be like:
curl or hit the actual API you're calling.
Log/Copy the response and try to parse it with JSON.parse. If you're getting error, fix it.
If not, make sure your code is not mutating/changing the original response.
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.
For future googlers:
This message will be generated if the server-side function crashes.
Or if the server-side function doesn't even exist ( i.e. Typo in function name ).
So - suppose you are using a GET request... and everything looks perfect and you've triple-checked everything...
Check that GET string one more time. Mine was:
'/theRouteIWant&someVar=Some value to send'
should be
'/theRouteIWant?someVar=Some value to send'
^
CrAsH ! ( ... invisibly, on the server ...)
Node/Express sends back the incredibly helpful message:
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
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>
2022 UPDATE: having written this several years ago. I'd call this suggestion more of a workaround - a direct fix. The better hosting pattern is to simply not try to host these api paths under your website path; rather, host them on separate base URLs entirely. For my use case example, the API and Web path would be entirely separate Azure Web Services and would get different URL endpoints.
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.
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.
Make sure that response is in JSON format otherwise fires this error.
I got the same error while calling an API in React using the fetch API with the POST method.
Before:
fetch('/api/v1/tour',{
method:"POST",
headers:{"Content-type":"json/application"},
body:JSON.stringify(info)
})
.then((response)=>response.json())
.then((json)=>{
if(json.status === 'success')
alert(json.message)
else
console.log('something went wrong :(')
}).catch(e=>console.log(e))
I resolved the error by changing the headers to {"Content-type":"application/json"}:
After:
fetch('/api/v1/tour',{
method:"POST",
headers:{"Content-type":"application/json"},
body:JSON.stringify(info)
})
.then((response)=>response.json())
.then((json)=>{
if(json.status === 'success')
alert(json.message)
else
console.log('something went wrong :(')
}).catch(e=>console.log(e))
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.
The possibilities for this error are overwhelming.
In my case, I found that the issue was adding the homepage filed in package.json caused the issue.
Worth checking: in package.json change:
homepage: "www.example.com"
to
hompage: ""
Malformed JSON or HTML instead of JSON is the underlying cause of this issue, as described by the other answers, however in my case I couldn't reliably replicate this error, as if the server was sometimes returning valid JSON, and other times returning something else like an HTML error page or similar.
In order to avoid it breaking the page altogether, I resorted to manually trying to parse the returned content, and share it in case it helps anyone else resolve it for them.
const url = "https://my.server.com/getData";
fetch(url).then(response => {
if (!response.ok) return; // call failed
response.text().then(shouldBeJson => { // get the text-only of the response
let json = null;
try {
json = JSON.parse(shouldBeJson); // try to parse that text
} catch (e) {
console.warn(e); // json parsing failed
return;
};
if (!json) return; // extra check just to make sure we have something now.
// do something with my json object
});
});
While this obviously doesn't resolve the root cause of the issue, it can still help to handle the issue a bit more gracefully and take some kind of reasonable action in instances when it fails.
For the React app made by CRA there are two main problems we might face while fetching the JSON data of any <dummy.json>
file.
I have my dummy.json file in my project and am trying to fetch the JSON data from that file but I got two errors:
"SyntaxError: Unexpected token < in JSON at position 0 .
I got an HTML file rather than actual JSON Data in the response in the Network tab in Chrome or any browser.
Here are the main two reasons behind that which solved my issue.
Your JSON data is invalid in your JSON file.
It might be that the JSON file did not load properly for this so you just restart your React server. This is my issue, within React.
React direct running or access the public folder not the src folder.
How I solved it:
I moved my file into the public folder and access is directly in any file of the src folder.
Making a REST call in the Redux action.js:
export const fetchDummy = ()=>{
return (dispatch)=>{
dispatch(fetchDummyRequest());
fetch('./assets/DummyData.json')
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(result => {
dispatch(fetchDummySuccess(result))
})
.catch(function (err) {
dispatch(fetchDummyFailure(err))
})
}
}
This might be old. But it just occurred in Angular where 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)
});
},
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.
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)';
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;
}
}
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
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.
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"
In my case (backend), I was using res.send(token);
Everything got fixed when I changed to res.send(data);
You may want to check this if everything is working and posting as intended, but the error keeps popping up in your front-end.
In my Case there was problem with "Bearer" in header ideally it should be "Bearer "(space after the end character) but in my case it was "Bearer" there was no space after the character. Hope it helps some one!
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.
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.
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.
SyntaxError: Unexpected token < in JSON at position 0
You are getting an HTML file (or XML) instead of json.
Html files begin with <!DOCTYPE html>.
I "achieved" this error by forgetting the https:// in my fetch method:
fetch(`/api.github.com/users/${login}`)
.then(response => response.json())
.then(setData);
I verified my hunch:
I logged the response as text instead of JSON.
fetch(`/api.github.com/users/${login}`)
.then(response => response.text())
.then(text => console.log(text))
.then(setData);
Yep, an html file.
Solution:
I fixed the error by adding back the https:// in my fetch method.
fetch(`https://api.github.com/users/${login}`)
.then(response => response.json())
.then(setData)
.catch(error => (console.log(error)));
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 <.
In my case, I was getting this running webpack. It turned out to be corrupted somewhere in the local node_modules dir.
rm -rf node_modules
npm install
...was enough to get it working right again.
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 will run into similar issues.
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.
I was facing the same issue.
I removed the dataType:'json' from the $.ajax method.
Those who are using create-react-app and trying to fetch local json files.
As in create-react-app, webpack-dev-server is used to handle the request and for every request it serves the index.html. So you are getting
SyntaxError: Unexpected token < in JSON at position 0.
To solve this, you need to eject the app and modify the webpack-dev-server configuration file.
You can follow the steps from here.
In a nutshell, if you're getting this error or a similar error, that means only one thing: Someplace in our codebase, we were expecting a valid JSON format to process, and we didn't get one. For example,
var string = "some string";
JSON.parse(string)
will throw an error, saying
Uncaught SyntaxError: Unexpected token s in JSON at position 0
Because, the first character in string is s & it's not a valid JSON now. This can throw error in between also. like:
var invalidJSON= '{"foo" : "bar", "missedquotehere : "value" }';
JSON.parse(invalidJSON)
Will throw error:
VM598:1 Uncaught SyntaxError: Unexpected token v in JSON at position 36
because we intentionally missed a quote in the JSON string invalidJSON at position 36.
And if you fix that:
var validJSON= '{"foo" : "bar", "missedquotehere" : "value" }';
JSON.parse(validJSON)
will give you an object in JSON.
This error can be thrown in any place & in any framework/library. Most of the time you may be reading a network response which is not valid JSON. So steps of debugging this issue can be like:
curl or hit the actual API you're calling.
Log/Copy the response and try to parse it with JSON.parse. If you're getting error, fix it.
If not, make sure your code is not mutating/changing the original response.
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.
For future googlers:
This message will be generated if the server-side function crashes.
Or if the server-side function doesn't even exist ( i.e. Typo in function name ).
So - suppose you are using a GET request... and everything looks perfect and you've triple-checked everything...
Check that GET string one more time. Mine was:
'/theRouteIWant&someVar=Some value to send'
should be
'/theRouteIWant?someVar=Some value to send'
^
CrAsH ! ( ... invisibly, on the server ...)
Node/Express sends back the incredibly helpful message:
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
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>
2022 UPDATE: having written this several years ago. I'd call this suggestion more of a workaround - a direct fix. The better hosting pattern is to simply not try to host these api paths under your website path; rather, host them on separate base URLs entirely. For my use case example, the API and Web path would be entirely separate Azure Web Services and would get different URL endpoints.
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.
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.
Make sure that response is in JSON format otherwise fires this error.
I got the same error while calling an API in React using the fetch API with the POST method.
Before:
fetch('/api/v1/tour',{
method:"POST",
headers:{"Content-type":"json/application"},
body:JSON.stringify(info)
})
.then((response)=>response.json())
.then((json)=>{
if(json.status === 'success')
alert(json.message)
else
console.log('something went wrong :(')
}).catch(e=>console.log(e))
I resolved the error by changing the headers to {"Content-type":"application/json"}:
After:
fetch('/api/v1/tour',{
method:"POST",
headers:{"Content-type":"application/json"},
body:JSON.stringify(info)
})
.then((response)=>response.json())
.then((json)=>{
if(json.status === 'success')
alert(json.message)
else
console.log('something went wrong :(')
}).catch(e=>console.log(e))
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.
The possibilities for this error are overwhelming.
In my case, I found that the issue was adding the homepage filed in package.json caused the issue.
Worth checking: in package.json change:
homepage: "www.example.com"
to
hompage: ""
Malformed JSON or HTML instead of JSON is the underlying cause of this issue, as described by the other answers, however in my case I couldn't reliably replicate this error, as if the server was sometimes returning valid JSON, and other times returning something else like an HTML error page or similar.
In order to avoid it breaking the page altogether, I resorted to manually trying to parse the returned content, and share it in case it helps anyone else resolve it for them.
const url = "https://my.server.com/getData";
fetch(url).then(response => {
if (!response.ok) return; // call failed
response.text().then(shouldBeJson => { // get the text-only of the response
let json = null;
try {
json = JSON.parse(shouldBeJson); // try to parse that text
} catch (e) {
console.warn(e); // json parsing failed
return;
};
if (!json) return; // extra check just to make sure we have something now.
// do something with my json object
});
});
While this obviously doesn't resolve the root cause of the issue, it can still help to handle the issue a bit more gracefully and take some kind of reasonable action in instances when it fails.
For the React app made by CRA there are two main problems we might face while fetching the JSON data of any <dummy.json>
file.
I have my dummy.json file in my project and am trying to fetch the JSON data from that file but I got two errors:
"SyntaxError: Unexpected token < in JSON at position 0 .
I got an HTML file rather than actual JSON Data in the response in the Network tab in Chrome or any browser.
Here are the main two reasons behind that which solved my issue.
Your JSON data is invalid in your JSON file.
It might be that the JSON file did not load properly for this so you just restart your React server. This is my issue, within React.
React direct running or access the public folder not the src folder.
How I solved it:
I moved my file into the public folder and access is directly in any file of the src folder.
Making a REST call in the Redux action.js:
export const fetchDummy = ()=>{
return (dispatch)=>{
dispatch(fetchDummyRequest());
fetch('./assets/DummyData.json')
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(result => {
dispatch(fetchDummySuccess(result))
})
.catch(function (err) {
dispatch(fetchDummyFailure(err))
})
}
}
This might be old. But it just occurred in Angular where 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)
});
},
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.
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)';
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;
}
}
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
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.
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"
In my case (backend), I was using res.send(token);
Everything got fixed when I changed to res.send(data);
You may want to check this if everything is working and posting as intended, but the error keeps popping up in your front-end.
In my Case there was problem with "Bearer" in header ideally it should be "Bearer "(space after the end character) but in my case it was "Bearer" there was no space after the character. Hope it helps some one!
I get this error every time I try to use the POST method in my API.
SyntaxError: Unexpected end of JSON input at fetch.then.response
When I use the GET method I get the data normally.
This is the code:
const teste = () => {
fetch("myURL/test", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
id: 1,
name: "Teste",
amount: 1,
value: 3
})
})
.then(response => response.json()) //Here is the error
.then(data => {
console.log(data);
})
.catch((err)=>console.log(err))}
Can someone help me? Thank you.
EDIT:
I just add this line to see the log:
.then(response => console.log(response))
Here is what I got:
Response {
type: "cors",
url: "myURL/test",
redirected: false,
status: 201,
ok: true,
…}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 201
statusText: ""
type: "cors"
: "myURL/test"
__proto__: Response
It means that the page fetched at myURL/test does not responds with JSON content, or with malformed JSON content. This is not an error in your script, which is fine, this is an error with your server, that is not serving JSON content at myURL/test.
Also, note that servers might not respond similarly to GET requests and POST request for the same URL! If you fetch valid JSON from a GET request but, as you described, failed to fetch valid JSON from a POST request, your server might be serving different content depending on the request type. Investigate that.
Debug tips
Replace then(resp => resp.json()) by then(resp => resp.text()).then(console.log) to see what the served content looks like
Use Postman to simulate API calls, and see what the served content looks like, with more details
Examine the response with the developer tools:
In Chrome
Open the console (F12)
Go to the network tab
Click on the file server by myURL/test
Click on response: that will be the text content. It shoud be properly formatted JSON.
Basically GET method does not send your body object to the server in which you get the response. Only the POST action will send your body object to the server.
I assume that the object you wish to send is the problem. Either the server which you are trying to connect does not expects the body object as string or you should make sure you have parsed the JSON properly before processing.
Looks like the API you're calling, doesn't have a response body on this particular POST. Then when you call response.json() (converting response.body to json) it runs into error.
Or maybe the response is body is not a valid json body.
If you wanna handle this error more fashion way you could go like this:
tryGetJson = async (resp) => {
return new Promise((resolve) => {
if (resp) {
resp.json().then(json => resolve(json)).catch(() => resolve(null))
} else {
resolve(null)
}
})
}
https://github.com/github/fetch/issues/268#issuecomment-399497478
(for people coming later but dealing with this problem)
The problem is most probably server error or invalid URL but you can't see it because all examples on internet how to work with fetch are missing one important part - the server or network failure.
I think the correct way how to deal with fetch is test response if contains errors before conversion to json.
Check the part of the first then in example where it.ok is tested:
async function fetchData() {
return await fetch('https://your-server.com/some-NOt-existing-url/')
.then(it => {
if (!it.ok) {
throw `Server error: [${it.status}] [${it.statusText}] [${it.url}]`;
}
return it.json();
})
.then(receivedJson => {
// your code with json here...
})
.catch(err => {
console.debug("Error in fetch", err);
setErrors(err)
});
}
(note: it is just name convention borrowed from Kotlin, it makes JavaScript code shorter. It is alias for anything on left side of expression so in this case for response)
I'm just following tutorials and figuring out how to handle get requests in NodeJS.
Here are snippets of my code:
NodeJS:
router.get('/test', function(request, response, next) {
console.log("Received Get Request");
response.jsonp({
data: 'test'
});
});
Angular:
$http.get("http://localhost:3000/test").
success(function(response) {
alert("OK");
}).
error(function(response) {
alert("FAIL");
});
If I try to access the link directly # localhost:3000/test, I'm able to receive the JSON message correctly. But when I use angularJS $http call, the request always fails and I'll find this error in the network inspector (Response)
SyntaxError:JSON.parse:unexpected end of data at line 1 column 1 of
the JSON data
The reason for that is because the response is empty but the response code is 200 in both cases.
I've tried searching for hours but maybe someone can enlighten me on this?
you could try and send
res.send('test')
and then on your http request you can use 'then'
$http.get("http://localhost:3000/test").then(function(res) {
console.log(res);
})
unlike success, then will give you a complete object (with 'test' - string as res.data)
success will bring you only the data;
then will bring you the whole object (with the status and such)..
now about that jsonp .. it's used to override a json response. you could simply use 'res.json({data: 'test'})' and it should also work for you..
hope it helps
You're using jsonp in node, which you probably don't need to. This adds extra characters to the response and so the JSON parser fails to parse (that's what the error is telling you, the JSON is malformed)
Try changing the server to look like
response.json({
data: 'test'
});
If you look in the Network pane of the developer tools, you should be able to see the raw response. It should look something like:
{"data" : "test"}