SyntaxError: Unexpected token < in JSON at position 0
while retrieving json data using ionic 2
here is the link http://areeef.unaux.com/php/platforms.php
here is the code i am using to get json data
constructor( public navCtrl: NavController, private http: Http) {
this.http.get('http://areeef.unaux.com/php/platforms.php').map(res => res.json()).subscribe(data => {
console.log(data);
}); }
when i run the same php code in local host then i can run the app without any error. but in online sever it is giving the error mentioned above
so is that a problem of the server or error in my code?
Nothing seems wrong with the code. The problem is because your server not returning valid JSON.
Check the API's behaviour using postman plugin. I have checked it and it returning invalid JSON-
This site requires Javascript to work, please enable Javascript in
your browser or use a browser with Javascript support
So, get your api working on postman first.
This error is normally caused by the server returning non JSON data. In this case, the PHP script could be returning an error message in form of HTML which will cause an error. The best approach for such errors is to debug the PHP script independently or accommodate the possibility of getting both html and JSON data on the client side.
Related
I'm using Superagent in my react app, and i'm making some call's to the IPFS api. Specifically, I am uploading files to my IPFS server. Now, everything works, When I upload one or multiple files the call goes through and the files show up in IPFS no problem.
A problem occurs when I upload multiple files though, the response seems to come back as plain text, instead of JSON, and superagent throws the error
client.js:399 Uncaught (in promise) Error: Parser is unable to parse the response
at Request.<anonymous> (client.js:399)
at Request.Emitter.emit (index.js:133)
at XMLHttpRequest.xhr.onreadystatechange (client.js:708)
So to be clear, when uploading a single file, I get a nice JSON response, but when I upload multiple files, the response is in plain text.
Can I force Superagent to give me the response back and parse it myself? Or can I set something when making the call so that it forces a json parse? Below is my superagent request function
add : acceptedFiles => {
const url = ipfs.getUrl("add")
const req = request.post(url)
acceptedFiles.forEach(file => req.attach(file.name, file))
req.then(res => {
return console.log(res);
})
}
I'm searching for this for a more elegant solution, but before I would have found it , I'd like to provide my own solution.
I think this problem caused by wrong responsive Content-Type set, but I've not confirmed this opinion yet.
However, you can try this:
req.catch(function (err) {
console.log(err.rawResponse)
})
At least, this solves my problem.
According to their docs you can specify custom parser that will take precedence over built-in parser:
You can set a custom parser (that takes precedence over built-in parsers) with the .buffer(true).parse(fn) method. If response buffering is not enabled (.buffer(false)) then the response event will be emitted without waiting for the body parser to finish, so response.body won't be available.
I tried and it worked well for me.
superagent.get('....')
.buffer(true)
.parse(({ text }) => JSON.parse(text))
.then(...)
I'm presently working on a phx / phoenix API written in Elixir. And I have created a frontend for the API using React.js. However, I'm getting the below error message in the JS console of the browser.
I have successfully created a user using Postman, so I'm 99% sure the error isn't with the phx project, but rather somewhere with the React project.
I have both the frontend and backend hosted on github. And a .env file will need to be created in the root of the React project with the below line,
REACT_APP_API_URL=http://localhost:4000/api
and was working my way through the following tutorial.
Any and all help would greatly be appreciated.
The output of localStorage.getItem("token") being
eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJVc2VyOjEiLCJleHAiOjE0ODcyODI4ODcsImlhdCI6MTQ4NDY5MDg4NywiaXNzIjoiUGhvZW5peENoYXQiLCJqdGkiOiIwNzFlYzgwYi0wZmYzLTQyYzgtODA3Mi1kNzViZmVhZTg4NWEiLCJwZW0iOnt9LCJzdWIiOiJVc2VyOjEiLCJ0eXAiOiJhY2Nlc3MifQ.NsuqH50HooK8vjFfHtPH9iXSykZ9oYA0ul4b_C5fQtpu_zFvNNy-skcv9HI2i25X-NlB-9xOr-xzh2abnrpYUw
suggests that for some reason, the app stored the token without passing it through JSON.stringify, and calling JSON.parse on this string throws the Unexpected token e error, as expected.
I did not see any localStorage.setItem without JSON.stringify in the current code, so the token was probably stored like that in a previous version of the app. You should try clearing it manually and logging in again.
When we get the non-JSON response, we get such error..
To avoid such error, mention the responseType: Text in your api endpoint call.
This will work,
return this.http.post(`${environment.apiUrl}/login`, user, {responseType: 'text'});
This will not work(If you mention type),
return this.http.post<string>(`${environment.apiUrl}/login`, user, {responseType: 'text'});
This error message usually means you're getting a non-JSON response. If you look at the raw response in the Network tab of your debugger, you should be able to see what you're getting back from the server.
In my app, after get "https://dl.boxcloud.com/*" url and send it to the View API, I receive this error:
{
message: "JSON parse error - No JSON object could be decoded"
type: "error"
request_id: "3ef12abcaf7a4c5abab5fb0d3959255e"
}
you can use this chrome extension to recreate this error
https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo
I tried with the other rest clients and it work correctly. Except in my app and the extension above.
I tried with the other rest clients and it work correctly. Except in my app and the extension above.
If this is the case, it's likely that the client you're using isn't actually sending properly formatted JSON. One way to debug this would be to output the raw HTTP request the client is sending and ensuring that it's actually sending the JSON properly.
Need to fetch the build values from apache.org. So i am using their api
https://builds.apache.org/api/json
I tried angularjs $http.jsonp but not able to fetch the data.
In chrome console under network json api is getting loaded but the data is not getting returned instead it is throwing the response as error.
app.controller("jsoncontroller",function($scope,$http){
var url='https://builds.apache.org/api/json';
$http.jsonp(url).success(function(data){
console.log('success');
})
.error(function () {
console.log('error')
});
});
Getting the error as
Uncaught SyntaxError: Unexpected token :
error
As per the jsonp angular docs, you must append JSON_CALLBACK to the URL: https://builds.apache.org/api/json?jsonp=JSON_CALLBACK
However, that URL doesn't work because even when the callback parameter is specified, the server still sends back a content-type of application/json, instead of the expected application/javascript. This causes it to be parsed (evidently) by the json parser instead of the javascript callback needed for JSONP to work. I'm not versed enough in JSONP or Angular to know who is it fault here.
I've made a fiddle with this working with another URL.
[Update]: The apache build server appears to use Jenkins, which has disable JSONP from the remote API. You can verify this yourself by trying to hit their jsonp endpoint, which returns a 403. You'll have to use another endpoint, no way I can see around this.
I'm trying to query the Spotify Metadata API with AngularJS but I keep running into the following error.
Uncaught SyntaxError: Unexpected token :
Now I know typically when querying you should add callback=JSON_CALLBACK as a query string but in this case it won't work. It returns:
Failed to load resource: the server responded with a status of 400 (Bad Request)
I am using $http.jsonp().
Example without callback | Example with callback
So, is there a way around this using pure Javascript or I'm best add a server-side wrapper (which I've got working but rather if it was pure Javascript)?
It doesn't seem like Spotify is providing jsonp support, but they do support CORS - so this should work:
function spotify_api($http) {
var url = "http://ws.spotify.com/lookup/1/.json?uri=spotify:track:5PJSqY8jbYzr4a6dl5Ory1";
//CORS support
delete $http.defaults.headers.common['X-Requested-With'];
$http.get(url).success(function(data) {
console.log(data);
});
}
See my update: http://jsfiddle.net/69kYH/
The bad news is that CORS doesn't seem to work properly in angular with older versions of IE - see AngularJS - Calling Flickr API fails with warning message