Consuming RESTful service with angularJS - angularjs

I've set up a REST service, using Spring framework. The service, simply reads some info from database, and represents it in JSON format. The service works properly when accessing it directly via browser (i.e: http://localhost:8080/infractions/get?no=2 works just fine.) But, when I try to access it using angularJS, it doesn't show anything! I've followed this tutorial provided by Spring official website, and here's how my code looks like:
index.html file:
<!doctype html>
<html ng-app>
<head>
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="get.js"></script>
</head>
<body>
<div ng-controller="getFractionByID">
<p>Fraction Type is: {{get.name}}</p>
</div>
</body>
</html>
get.js file:
function getFractionByID($scope, $http) {
$http.get('http://localhost:8080/infractions/get?no=2').
success(function(data) {
$scope.get = data;
});
}
I'm really new to non-academic programming and I'm rather inexperience, so please help me find out where should I start finding the problem?
Update: Error message:
XMLHttpRequest cannot load http://localhost:8080/infractions/get?no=2. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Related

Can babel-standalone be used if index.html is served locally ? (no webserver)

Before i start the question, here is what i already know to avoid answers along the same lines.
TL;DR: I already know I can use a webserver and serve the index.html as http://localhost:8081/index.html and it will work.
Now for the question details:
I have created a minimal react-js app, referencing babel-standalone in the index.html file as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Minimal</title>
</head>
<body>
<div id='divRootComponent'></div>
<!-- react reasonably latest for oct/2018 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.2/umd/react-dom.production.min.js"></script>
<!-- babel -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<!-- react CUSTOM component.. i.e. myApp's entry point -->
<script type="text/babel" src="index.js"></script>
</body>
</html>
and the index.js contents are:
class YoSupComponent extends React.Component {
constructor () {
super();
this.state = {
message: 'whatever...'
};
}
componentDidMount() {
console.log('YoSupComponent.componentDidMount');
}
render () {
return (
<div>
Yo ! Dude or Dudette... sup ?
</div>
);
}
}
const props = {}; //none for now...
ReactDOM.render(<YoSupComponent {...props} />
, document.getElementById('divRootComponent'))
When I tried to access the index.html file in the Browser via file:///path/to/index.html, the error is:
Access to XMLHttpRequest at 'file:///D:/path/to/index.js' from origin
'null' has been blocked by CORS policy: Cross origin requests are
only supported for protocol schemes: http, data, chrome,
chrome-extension, https. # babel.min.js:24
So thinking the problem is related to the script tags referencing files remotely, I download react and babel locally, and make references local; then again I access file:///path/to/index.html.
Still get the same error ! whats going on? a) why does babel even use XMLHttpRequest (as per the error message) when the babel.js file is now local ? b) why no such message for react files ?
According to MDN, if you specify a script tag with a type that's not text/javascript, it will be ignored by the browser:
The embedded content is treated as a data block which won't be processed by the browser. Developers must use a valid MIME type that is not a JavaScript MIME type to denote data blocks. The src attribute will be ignored.
In other words, the browser does not load or run index.js in your example. This makes sense - if it did, you'd get a syntax error, as your browser can't understand JSX.
What actually happens is that the babel-standalone script looks at your HTML, finds all of the script tags marked text/babel, loads them via XMLHttpRequest, and then compiles and runs them.
This is why you're getting CORS errors - the browser's not loading the file, the script is. Unfortunately, I don't think you can resolve this without using a web server or compiling your Babel code ahead of time.

Angular grabbing JSON params with $http.get for one url but on another

I'm new with Angular and trying to get some basic UI stuff going. I have a RESTful Spring service up and running. When I curl my service :
curl http://myPersonalSite.com:1313/service/event?id=1
I get a JSON response containing stuff including an "id", "description", etc.
Using the identical code, but switching out the URL for the one given in an example I'm following
curl http://rest-service.guides.spring.io/greeting
I also get a JSON response with "id", and "content".
The example url results in the ID showing up when I run
spring run app.groovy
... but when I switch it out for my service URL, the id is not displayed. It doesn't seems to be able to get any info off the JSON response from my service. What am I missing here?!?
/public/index.html :
<html ng-app="demo">
<head>
<title>Hello AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="hello.js"></script>
</head>
<body>
<div ng-controller="Hello">
<p>The ID is {{event.id}}</p>
</div>
</body>
/public/hello.js :
angular.module('demo', [])
.controller('Hello', function($scope, $http) {
$http.get('http://rest-service.guides.spring.io/greeting'). // this works
//$http.get('http://myPersonalSite.com:1313/service/event?id=1'). // this doesn't work
then(function(response) {
$scope.event = response.data;
});
});
app.groovy - simply :
#Controller class JsApp { }
... and then I run spring run app.groovy and the example URL renders the id fine in the browser but my URL renders the page but there is no id. Again, curl for both URLs returns JSON which both contain and "id" key. I have read up a bit on JSON strings vs objects, and that doesn't seem to be the issue, here. Any help would be greatly appreciated.
note - the following thread is similar, but slightly different jQuery - .get works for 1 URL but not another
I guess your request is blocked by CORS policy. You can check your browser console if there is any error message like "...has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource".
The rest-service response actually set the Access-Control-Allow-Origin if you check the network tab of Chrome.
Browser will block ajax request if the requested resource's domain is different with the page domain and no proper Access-Control-Allow-Origin header is not set at server side.

Can't run project locally due to "Failed to load resource: net::ERR_EMPTY_RESPONSE" in Learning AngularJS Chapter 2 by Ken Williamson

I can't figure out why I'm getting the ERR_EMPTY_RESPONSES error below. I am working on Chapter 2 of Learning AngularJS by Ken Williamson. I typed in all the code exactly as it is in the book and set up the directory structure exactly as it is listed in the book. However, when I try to run the project (locally on my computer), I get the following error:
Failed to load resource: net::ERR_EMPTY_RESPONSE (22:27:47:397 | error, network)
at http://localhost:8383/AngularJsHelloWorld_chapter2/partials/main.html
Error: [$compile:tpload] http://errors.angularjs.org/1.5.0-rc.0/$compile/tpload?p0=partials%2Fmain.html&p1=-1&p2=
at Error (native)
The code for the relevant pages look like this:
Index.html:
<!DOCTYPE html>
<html lang="en" ng-app="helloWorldApp">
<head>
<title>AngularJS Hello World</title>
<meta name="viewport" content="width=device-width, initial- scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="js/libs/jquery-1.11.3.min.js"></script>
<script src="js/libs/angular.min.js"></script>
<script src="js/libs/angular-route.min.js"></script>
<script src="js/libs/angular-resource.min.js"></script>
<script src="js/libs/angular-cookies.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
main.html:
<div>{{message}}</div>
I realize I might need to provide additional information. Any help is appreciated.
Here is a link to the directory structure:
https://library.oreilly.com/book/0636920035831/learning-angularjs/14.xhtml?ref=toc#idp2844416
Here is the code on Github: https://library.oreilly.com/book/0636920035831/learning-angularjs/14.xhtml?ref=toc#idp2844416
By the way, my directory is slightly different from the book in that I have the latest versions of the js framework in it.
This error is caused by a known issue in ngRoute (https://docs.angularjs.org/api/ngRoute):
If ngView is contained in an asynchronously loaded template (e.g. in another directive's templateUrl or in a template loaded using ngInclude), then you need to make sure that $route is instantiated in time to capture the initial $locationChangeStart event and load the appropriate view. One way to achieve this is to have it as a dependency in a .run block: myModule.run(['$route', function() {}]);
Adding the following code should fix the error. It did for me when opening the web page locally.
helloWorldApp.run(['$route', function() {}]);

Issue reading from my Slim PHP API through Angularjs using ngResource

I've recently completed a Slip PHP API build which interacts beautifully with my Android application. I'm now building a web front-end and for the life of me I can't understand how to request information via GET using ngResource's query function.
My index.html file is:
<!doctype html>
<html ng-app="discussApp">
<head>
</head>
<body>
<div ng-controller="topicsController">
<div>{{ topics }}</div>
</div>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/angular-resource.min.js"></script>
<script type="text/javascript" src="js/angular-route.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
My app.js file:
var app = angular.module('discussApp', ['ngResource']);
app.controller("topicsController", function($scope, $resource, $http) {
var Topics = $resource("http://api.discussorama.com/v1/topics");
$scope.topics = Topics.query();
});
And the information I'm trying to read (I've successfully done this both from Chrome's Advanced REST Client, the browser, and my Android app) is at http://api.discussorama.com/v1/topics (Note: I've temporarily disabled my authentication middleware in Slim PHP to test with Angularjs). The endpoint returns a json response but I'm not seeing anything in Angular besides "[]". The link to the Angular app is http://hwaelapps.com/discuss/web if anyone would like to see exactly what is happening. Thanks in advance for the help. Note: I've tried several ngResource config options including urlencode but it's still not receiving the data so I stripped all that and all the code is directly as is in the question.
The answer was in the console log all along. The error I was receiving was:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
The solution was simply to add
header("Access-Control-Allow-Origin: *");
to my Slim API's index.php file. I guess my shared host isn't configured for CORS.

Boomerang beacon called via GET instead of POST

I took a freshly-cloned copy of the Boomerang library and ran make to produce the default boomerang.js script.
I copied that file, along with the following HTML document into a directory.
<html>
<head>
<script src="/boomerang.js" type="text/javascript"></script>
<script type="text/javascript">
BOOMR.init({
user_ip: "127.12.34.56",
beacon_url: "http://127.0.0.1:8008/beacon",
beacon_type: "POST"
});
</script>
</head>
<body>
<h1>Hello RUM</h1>
</body>
</html>
I then served that out of host running on port 8008 and viewed the html file. When I check the access log, I see
127.0.0.1 - - [17/May/2016:15:13:31 +0200] "GET /beacon?u=http%3A%2%2F127.0.0.1%3A8008%2Frum.html&v=0.9&...
That is, the Boomerang library is issuing a GET instead of POST and at a quick glance I can't figure out why. (The /beacon endpoint doesn't actually exist, so it throws a 404, but that is (I hope) beside the point). I'll take a closer look with dev tools, but has anyone experienced this before?

Resources