Angularjs issue $http.get not working - json

I am a novice to Angularjs and tried to follow example given for $http.get on angularjs website documentation.
I have a REST service, which when invoked returns data as follows:
http://abc.com:8080/Files/REST/v1/list?&filter=FILE
{
"files": [
{
"filename": "a.json",
"type": "json",
"uploaded_ts": "20130321"
},
{
"filename": "b.xml",
"type": "xml",
"uploaded_ts": "20130321"
}
],
"num_files": 2}
Part of the contents of my index.html file looks like as follows:
<div class="span6" ng-controller="FetchCtrl">
<form class="form-horizontal">
<button class="btn btn-success btn-large" ng-click="fetch()">Search</button>
</form>
<h2>File Names</h2>
<pre>http status code: {{status}}</pre>
<div ng-repeat="file in data.files">
<pre>Filename: {{file.filename}}</pre>
</div>
And my js file looks as follows:
function FetchCtrl($scope, $http, $templateCache) {
$scope.method = 'GET'; $scope.url = 'http://abc.com:8080/Files/REST/v1/list?&filter=FILE';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
}
But when I run this, I do not see any result for filenames and I see http status code = 0
When I run , http://abc.com:8080/Files/REST/v1/list?&filter=FILE in browser, I still can see desired results (as mentioned above)
I even tried to debug using Firebug in firefox, I see the above URL gets invoked when I hit "Search" button but response looks to be empty. And interestingly in Firebug under URL, it shows
OPTIONS "Above URL"
instead of
GET "Above URL"
Can you please let me know, what I am doing wrong and why I am not able to access JSON data ?
Thanks,

This is because how angular treats CORS requests (Cross-site HTTP requests). Angular adds some extra HTTP headers by default which is why your are seeing OPTIONS request instead of GET. Try removing X-Requested-With HTTP header by adding this line of code:
delete $http.defaults.headers.common['X-Requested-With'];
Regarding CORS, following is mentioned on Mozilla Developer Network:
The Cross-Origin Resource Sharing standard works by adding new HTTP
headers that allow servers to describe the set of origins that are
permitted to read that information using a web browser.

I have been having the issue using $resource, which also uses $http.
I noticed that when I used AngularJS 1.0.6 the request would not even show up in Firebug, but when using AngularJS 1.1.4 Firebug would show the GET request and the 200 OK response as well as the correct headers, but an empty response. In fact, the headers also showed that the data was coming back as shown by the "Content-Length" header having the correct content length, and comparing this against a REST Client plugin I was using that was successfully retrieving the data.
After being even further suspicious I decided to try a different browser. I had originally been using Firefox 16.0.1 (and also tried 20.0.1), but when I tried IE 9 (and AngularJS 1.1.4) the code worked properly with no issues at all.
Hopefully this will help you find a workaround. In my case, I noticed that I never had this problem with relative URLs, so I'm changing my app around so that both the app and the API are being served on the same port. This could potentially be an AngularJS bug.

I had the same problem today with firefox. IE worked fine. I didn't think it was cors at first because like you I got no errors in the console and got a status of 0 back in my error method in angular. In the firefox console I was getting a 200 response back in my headers and a content length, but no actual response message. Firefox used to give you a warning about cross site scripting that would point you in the right direction.
I resolved the issue by setting up cors on my api. This is really the best way to go.
If you are only using GET with your api you could also try using jsonp this is built right into angular and it is a work around for cors when you do not control the api you are consuming.
$http.jsonp('http://yourapi.com/someurl')
.success(function (data, status, headers, config) {
alert("Hooray!");
})
.error(function (data, status, headers, config) {
alert("Dang It!");
});

It's cross-site-scripting protection.
Try starting google chrome with --disbable-web-security (via command line).
If that isn't working also try to put your angular stuff into an http server instead of using the file protocol. (Tip: use chrome canary if you want to have a browser dedicated to --disable-web-security - of course you'll have to set the command line argument too, but both chrome versions run simultaneously). For release you'll have to set some http headers on the server providing the AngularJS-stuff to allow access to the twitter api or whatever you want to call.

Related

Returning JSON through angular and bible.org api or esvapi.org

I've been researching this and cannot find or understand some of the solutions so i'm hoping to get some help here. I'm using Asp.net and building an application that needs to use a bible api. I like the two listed in the question. Every time I call esvapi it comes back successful, but I cannot view the data. I get an error in the console.
XMLHttpRequest cannot load http://www.esvapi.org/v2/rest`/passageQuery?key=8834092f0c58fcda&passage=James2. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:59324' is therefore not allowed access.`
I've seen other with this error and I have questions.
If I'm understanding this correct I get this because the server is preventing me from seeing the data for security purposes. Maybe even the browser( this is not just a chrome issue) problem. So if I need to add a info to the response header from Angularjs to stop this how is that done. Anyone with experience?
Would I need to contact anyone to be able to prevent the server from responding this way...I doubt this, but thought I would ask. I already have valid api key.
the bible.org website api key is confusing to apply to my code. on esvapi i just add a header with key: "keypass" and I only have the CORS issue. But with bible.org I can't figure out how to implement the api key and password. see below... Do I say token:key: username. If i put the api in the browser I get a popup to add username and password. the username is my key and the password is ignored. I tried putting in username as key, but that didn't cut it. Regardless I need to fix the CORS issue and add info to response headers to see response data.
$scope.search = function() {
return $http.get("http://www.esvapi.org/v2/rest/passageQuery?&passage=" + $scope.bo + $scope.chap, {
headers: {
"key?token?orusername?": "",
///thought i saw someone do this...don't know if this is right
"Access-Control-Expose-Headers": "Content-Disposition",
}
}).success(function (data, status, headers, config) {
$scope.book = data.Book;
$scope.chapter = data.Chapter;
$scope.output = data.Output;
}).error(function (data, status, headers, config) {
$scope.message = "Oops... something went wrong";
});
Any input would be helpful. Thanks!
I actually have a bible api working...just a version that I don't like and there is not another version on that webites api.
Change the get $http.get call to $http.jsonp and hope it works. You're using cross-site scripting. Sometimes you can get away with a JSONP call in these cases and sometimes you can't.

How get data from rest api URL in angularJs? While i'm try to get its show me as 0kb file

function Hello($scope, $http) {
$http.get('http://localhost/api/Country')
.success(function(data, status) {
$scope.greeting = data;
}).error(function(data, status){
alert('Error');
});
}
URL: Try pull the data from url, it shown me as a 0kb file. when i click that URL directly in shown some data.
Tried on my application before you replace the url by localhost (I guess changed for security reason), seems to come from a wrong configuration on server side, not angular.
Firefox trigger an error saying :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/api/Country. This can be fixed by moving the resource to the same domain or enabling CORS.
If you are in charge of this server, you should give a look at Cross-Origin Request, but your angular code is correct, sorry :D

Cannot run xmlhttprequest in Chrome App : provisional headers & No 'Access-Control-Allow-Origin'

I am building a chrome app sending a Get HTTPRequest to an external API:
I get the answer:
XMLHttpRequest cannot load
http://developer.echonest.com/api/v4/artist/profile?api_key=FILDTEOIK2HBORODV&name=weezer.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'chrome-extension://ihdfphmemcdeadpnjkhpihmcoeiklphe'
is therefore not allowed access.
I did allow the external domain in permissions in my manifest (to prevent blocking in cross domain requests)
When I type the URL in the Address Bar it works perfectly
It seems Chrome is blocking my request, I even tried to load directly the script in an HTML page and it does not work (same message but with origin "null") (oh and it did not allow me to cheat by changing the Origin in the Header).
I also get the famous "Caution : Provisional Headers are shown" in the console, which makes me think Chrome is blocking my request, I looked up on other Stack Overflow Questions but apart running chrome://net-internals and looking for stuff I haven't the first clue about I cannot find any good answers (I did run chrome://net-internals but really can't make any sense out of it).
Here is the request :
function update_stations() {
var xhr = new XMLHttpRequest();
xhr.open("Get","http://developer.echonest.com/api/v4/artist/profile?api_key=FILDTEOIK2HBORODV&name=weezer", true);
xhr.responseType = "json";
xhr.onreadystatechange = function() {
console.log("Essai");
console.log(xhr.readyState);
console.log(xhr);
document.getElementById("resp").innerText = xhr;
}
xhr.send()
}
Any thoughts (would be highly appreciated)?
Cross-Origin XMLHttpRequest chrome developer documentation explains that the host must be listed in the permissions of the manifest file.
I've taken the XHR code from above and included it in the hello world sample. It works after adding the following to the manifest.json.
"permissions": [
"http://*.echonest.com/"
]

HTML5 Offline Functionality Doesn't Work When Browser Restarted

I am using the offline HTML5 functionality to cache my web application.
It works fine some of the time, but there are certain circumstances where it has weird behaviour. I am trying to figure out why, and how I can fix it.
I am using Sammy, and I think that might be related.
Here is when it goes wrong,
Browse to my page http://domain/App note: I haven't included a slash after the /App
I am then redirected to http://domain/App/#/ by sammy
Everything is cached (including images)
I go offline, I am using a virtual machine for this, so I unplug the virtual network adapter
I close the browser
I reopen the browser and browse to my page http://domain/App/#/
The content is showing except for the images
Everything works fine if in step #1 I browse to http://domain/App/ including the slash.
There are some other weird states it gets into where the sammy routes are not called, so the page remains blank, but I haven't been able to reliably replicate that.
??
UPDATE: The problem is that the above steps caused problems before. It is now working when I follow the above steps, so it is hard to say what is going on exactly. I am starting from a consistent state every time because I am starting from a snapshot in a VM.
My cache manifest looks like this,
CACHE MANIFEST
javascripts/jquery-1.4.2.js
javascripts/sammy/sammy.js
javascripts/json_store.js
javascripts/sammy/plugins/sammy.template.js
stylesheets/jsonstore.css
templates/item.template
templates/item_detail.template
images/1Large.jpg
images/1Small.jpg
images/2Large.jpg
images/2Small.jpg
images/3Large.jpg
images/3Small.jpg
images/4Large.jpg
images/4Small.jpg
index.html
I'm running into a similar issue as well.
I think part of the problem is that jquery ajax is misinterpreting the response. I believe sammy is using the jquery to make the ajax calls, which is leading to the errors.
Here's a code snippet i used to test for this (though not a solution)
this.get('#/', function (context) {
var uri = 'index.html';
// what i'm trying to call
context.partial(uri, {});// fails on some browsers after initial caching
// show's that jquery's ajax is misinterpreting
// the response
$.ajax({
url:uri,
success: function(data, textStatus, jqXHR){
alert('success')
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert('error')
if(jqXHR.status == 0){ // this is actually a success
alert(jqXHR.responseText);
}else{
alert('error code: ' + jqXHR.status) // probably a real error
}
}
});

Custom 404 error without server

Is possible to intercept 404 error without using web server (browsing html file in the filesystem) ?
I tried with some javascript, using an hidden iframe that preload the destination page and check for the result and then trigger a custom error or redirect to the correct page.
This work fine but is not good on perfomance.
A 404 error is an HTTP status response. So unless you are trying to retrieve this file using an HTTP request/response, you can't have a genuine 404 error. You can only mimic one in something like the way you suggest. Any "standard" way of handling a 404 error is dependent on your flavour of web server anyway...
404 is a HTTP response code, and as such only delivered through the HTTP protocol by servers that speak it. The file:// extension isn't a real protocol response as such, it's a hack built into clients (like browsers) that enable local file support, however it's up to browsers / clients themselves whether they expose any response codes from their file:// implementation. In theory they could report them in the DOM, for example, but they would be response codes exposed to themselves, and as such rarely implemented. Most don't, and there isn't a standard way for it. You may look into browser extensions, like Firefox, and see if they support it, but then, this is highly unstandard and will likely break if you pop it on the web.
Why don't you want to use the server?
I don't believe that it's possible to handle a 404 error client-side, because a 404 error is server-side.
Whenever you load a webpage, you make a request to the server. Thus, when you ask for a file that's not there, it's the server that handles the error. Regular HTML/CSS/JavaScript only come into the picture when the server sends back a response to tell you that it can't find the file.
Steve
Because I was looking for this today. You can now do this without a server by using a Service Worker to cache the custom 404 page, and then serve it when a fetch request status is 404. Following the instructions on the google cache lab, the worker files looks as follows:
const filesToCache = [
'/',
'404.html'
];
const staticCacheName = 'pages-cache-v1';
self.addEventListener('install', event => {
console.log('Attempting to install service worker and cache static assets');
event.waitUntil(
caches.open(staticCacheName).then(cache => {
return cache.addAll(filesToCache);
});
);
});
self.addEventListener('fetch', event => {
console.log('Fetch event for ', event.request.url);
event.respondWith(
caches.match(event.request).then(response => {
if (response) {
console.log('Found ', event.request.url, ' in cache');
return response;
}
console.log('Network request for ', event.request.url);
return fetch(event.request).then(response => {
console.log('response.status:', response.status);
// fetch request returned 404, serve custom 404 page
if (response.status === 404) {
return caches.match('404.html');
}
});
});
);
});