CORS between AngularJS and Java Jersey Rest - security

I have a Java Webapplication using jersey rest which gets deployed on a local tomcat server.
This application is developed and tested within eclipse IDE.
Now in aptana IDE I have a AngularJS webapp which should connecct (using REST) to the jersey webapplication.
What steps do I have to make to establish the connection? Out of the box its not running because of the different contexts.
My current angularJS call:
WinesApp.factory('Wine', function ($resource) {
return $resource('/WinesApp/rest/wines/:wineId', {}, {
update: {method:'PUT'},
query: {method:'GET', isArray:false}
});
});
Which should become somethign like:
WinesApp.factory('Wine', function ($resource) {
return $resource('http://localhost:port/WinesApp/rest/wines/:wineId', {port:':8080'}, {
update: {method:'PUT'},
query: {method:'GET', isArray:false}
});
});
Greets
Marc

For CORS to work you need to send the appropriate headers from the server: for Jersey, see for exmaple Java/Jersey: A CORS-Compliant REST API. Then you simply call it from JavaScript like you wrote (while not strictly RESTful, it's easier to restrict your API to use GET and POST requests only, no PUT and DELETE). Finally, the curl command line utility comes in handy to test the server.

Related

Node angular 2 integration

Hi I have a node based server api, and have created a simple web app using angular 2.But I don't understand how to integrate both. I have done a little research but most of the websites are only offering how to built angular 2 application and no one offers node integration.
Notice that Nodejs is simple server-side Javascript, so you have to follow one of these approches:
Server side web app:
In this case all pages (and functionality) will render in server-side. You can find lots of framework for doing that. So you need no client-side framework like angularjs.
Client side web app + server side api: I think that is something you need. Server side api has build as rest api service and serves all your business functionality. In client-side angular just consumes these services. All client based functionally will handle with angularjs (like routing, async service call, manages states and etc)
Or if your question is how comminucate with node-js rest api look at this page: angular2 http
You can install any web server for angular like apache or nginx. For example u're using apache, when you run apache you can access angular web through http://localhost/project.
Follow this tutorial on how to install and run nodejs http://blog.modulus.io/absolute-beginners-guide-to-nodejs on window. On mac https://shapeshed.com/setting-up-nodejs-and-npm-on-mac-osx/
You can call node server using REST API.
In your angular service for example :
$http.get('http://project/rest/getData', succFn).then(function (res) {
return succFn(res.data);
}, 'error');
In nodejs (REST Server) :
apiRoutes.get('/getData', function (req, res) {
// Return any data to client
res.json({
'code': '00',
'content': 'Return dummy or json here',
'remarks': 'Success'
});
}

Using socket.io with sails js

While there used to be very good documentation for using sockets, thanks to Irl Nathon's Sails Cast series. Things have changed in v0.11, with the sails team wrapping and burying the socket.io routines.
The sails site e.g. SailsSocket is maddeningly concise, saying what to do, but not how or where to do it, or if I need to npm or bower something. This has been particularly frustrating trying to use the sails.config.sockets talked about on the sails site. Which I cannot even find in my v0.11 directories.
First, I would like to know how and where to create my own response to a io.socket.get or .post or whatever. Right now when I do a get with something like:
`io.socket.request({
method: 'get',
url: '/sites/2',
params: {},
headers: {}
},function serverResponded(body, JWR){console.log("Body: ", JSON.stringify(body,null, 4)); console.log(' JWR: ', JWR.body)});'
I get back:
undefined
VM1149:7 "Not implemented in core yet"
VM1149:7 JWR: Not implemented in core yet
I can see the sites being called in the sails console, but nothing comes across.
I believe it is because I have defined my own routes and have my own find: function in my site controller and I manually need to push something into the server side socket. But I am confused as to how I am to call a whole page with HTTP and just the tables with socket.io in the same controller routine.
Where do I write my own low level socket.io routines that can be called from a web page?
Do I still do it in the app.js file?
Sails Cast showed it being done there, but again things have changed.
Sails "virtual requests" (what they call these socket.io-based HTTP-ish request) are generally used to retrieve or post JSON data to the server. Additionally, if a client-side script makes a virtual request, the server may add or remove the requesting socket to/from rooms.
Note that using a "virtual method" will ultimately run the same controller action, but will set req.isSocket = true.
This example is a view that renders a view for HTML-wanting requests but returns JSON data for socket-based requests:
...
// 'get /sites/:id': 'SomeController.showSite' (should be put in your `routes.js`)
showSite: function(req, res) {
// load something from the database
Site.findOne(req.param('id')).exec(function(err, site) {
// handler errors (same for HTTP or sockets)
if (err) return res.serverError();
if (!site) return res.notFound();
if (req.isSocket) return res.json(site); // render JSON response for our `site` object
else return res.view('sites/show', {site: site}); // render an HTML view
});
}
As for low-level socket.io, sails provides the global variable io (from sails.io.js), which is an instance of SailsSocket. It allows you to make HTTP-ish "virtual requests". More info here (although it seems you have already read all there is to read about SailsSocket :). You can access the underlying socket.io client with io.socket._raw.
// do this in the browser.
// sails.io.js should be included in layout.ejs by default.
io.socket.get('/site/2', console.log); // "virtual request"
// neat little trick ^^^^^^^^^^^ for testing :)
var rawIO = io.socket._raw;
rawIO.emit('some:event', "using native socket.io");
Hope this helps!

Explain the service.js in AngularJS

I'm quite new to AngularJS and NodeJS. I'm trying to develop an app using MEAN stack. I just looked through the sample code in the mean.io boilerplate. I created my own app referring the sample app. I'm trying to submit the AngularJS front end and expecting it to call NodeJs server side but it isn't working. I think service.js is messing up something. Here is the service code of sample app. Can any one explain what this code does with respect to Angular client side and NodeJS Server side.
'use strict';
//Articles service used for articles REST endpoint
angular.module('mean.articles').factory('Articles', ['$resource', function($resource) {
return $resource('articles/:articleId', {
articleId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}]);
It creates a new factory in angular called Articles. The Articles factory has the $resource service injected. The $resource object is used to setup an object for communicating with a RESTful service, in this case "articles/:articleId" the articleId will be pulled from the _id of the resource objects that are returned from queries using this $resource. When you call to update on one of the resources it will use the PUT HTTP Verb.
By itself this just defines the factory but doesn't actually make any calls you would need to inject this and use it somewhere like Articles.query();
From the docs
If the parameter value is prefixed with # then the value of that
parameter is extracted from the data object (useful for non-GET
operations).

build multiple layer restful API in node.js express

I am using node.js express to build simple rest API, I had built a API like
app.get('/sites/:site/:building/:floor',function(req,res){
var building = req.params.building, floor = req.params.floor, site = req.params.site;
console.log('query site ',site,building, floor);
.....
}
when client did the AJAX request in angular.js
$http.get('/sites/london')
.success(function(data) {
}).error(function(data, status, headers, config) {
});
the server doesn't respond to this kind of URL, unless I changed the express API to
app.get('sites/:site',function(){})
app.get('sites/:site/:building',function(){})
app.get('sites/:site/:building/:floor',function(){})
But the way above is too tedious so I wonder if it is possible to build API in one sentence app.get('sites/:site/:building/:floor',function(){})
The following stackoverflow answer should help you out. But to answer your question, the below should work
app.get('sites/:site?/:building?/:floor?',function(){})

Angular Frontend with JAX-RS backend

I have a RESTful Java backend which I made using Jersey, a JAX-RS implementation. This backend is running on a glassfish server on port 8084. I've also made some HTML5/JS/AJAX pages which display the data so I know my REST implementation is working.
I'm trying to develop an HTML5 / JS frontend for this application using the Angular.js framework but I'm experiencing some trouble. I have managed to develop some small webapps in angular which I'm running on Microsoft's IIS on port 80.
Unfortunately, there appears to be a problem with the communication between the two applications. Since I'm new to Angular, I'm unsure if I made a mistake in my frontend code, or if I'm experiencing CORS problems. I already tried running the backend on a Tomcat 7 with the CORS filter but that didn't solve anything.
My angular code looks like this:
services.js
var serviceModule = angular.module('ServiceModule', ['ngResource']);
serviceModule.factory('NodeService', function($resource) {
var NodeService = $resource('http://localhost:port/HtmlJerseyJava/service/node/get/3',{},
{
'get' : { method: 'GET',params:{port:':8084'}}
}
)
return NodeService;
});
controllers.js
function NodeDetailCtrl($scope, NodeService){
var node3 = NodeService.get();
$scope.data = JSON.stringify(node3) ;
}
I hardcoded the ID 3 for now, because I also need to figure out how I can pass the value of an input field from the view to the controller and then to the service. Eventually, the 3 in the service url would be replaced by a variable :nodeId
Any help would be greatly appreciated.
Try the following simplified code:
app.js (for test purposes I suggest you to put functions in one js file)
var serviceModule = angular.module('ServiceModule', ['ngResource']);
serviceModule.factory('Node', function($resource) {
return $resource('http://localhost:port/HtmlJerseyJava/service/node/get/3',{port:':8084'},
{
get {method:'GET'}
});
});
serviceModule.controller('NodeDetailCtrl', function($scope, Node){
$scope.data = Node.get();
}
It would be interesting to now what JSON data your client gets from the REST call.
Greets Marc
I found the solution. There were several steps to fix this problem:
Add a CORS filter to the Jersey servlet on Glassfish.
Upgrade the Angular version to 1.1.x (currently still unstable)
Set a custom header in your resource.
Enjoy a working application.
Big thanks Marcbaur for helping me out here.

Resources