Java – enable CORS to send requests from angularjs to Jersey

I tried to publish a JSON document from the angularjs application to the Jersey rest service If the request fails, notify me:

XMLHttpRequest failed to load http: / / localhost: 8080 / my rest. service / api / order / addOrder. The access control allowed source header does not exist on the requested resource Therefore, the original "http: / / localhost" does not allow access

Jersey rest post function

I enabled (I think it is) the appropriate title: the response of access control allow origin and access control allow – methods, as shown in the following method:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/addOrder")
public Response addOrder(DBObject dbobject) {
    DB db = mongo.getDB("staffing");
    DBCollection col = db.getCollection("orders");
    col.insert(dbobject);
    ObjectId id = (ObjectId)dbobject.get("_id");
    return Response.ok()
            .entity(id)
            .header("Access-Control-Allow-Origin","*")
            .header("Access-Control-Allow-Methods","GET,POST,DELETE,PUT")
            .allow("OPTIONS")
            .build();
}

Angle JS controller

I have declared the application and configured the $httpprovider and all the settings suggested in similar stack overflow:

var staffingApp = angular.module('myApp',['ngRoute','ui.bootstrap']);
myApp.config(['$httpProvider',function ($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
    $httpProvider.defaults.headers.common["Accept"] = "application/json";
    $httpProvider.defaults.headers.common["Content-Type"] = "application/json";
 }]);

I also created this controller to open a modal and process the form:

var modalCtrl = function($scope,$modal,$log,$http,$location) {          
    $scope.order = {
        activityTitle : null,anticipatedAwardDate : null,component : null,activityGroup : null,activityCategory : null,activityDescription : null
    };
    $scope.open = function () {
        var modalInstance = $modal.open({
            templateUrl: 'addOrder.html',windowClass: 'modal',controller: modalInstanceCtrl,resolve: {
                order : function () {
                    return $scope.order;
                    }
                }
            });
        modalInstance.result.then(function (oid) {
            $log.info("Form Submitted,headed to page...");
            $location.path("/orders/" + oid);
        },function() { 
            $log.info("Form Cancelled")
        });
    };
};

var modalInstanceCtrl = function ($scope,$modalInstance,order) {
    $scope.order = order,$scope.ok = function () {
        $log.log('Submitting user info');
        $log.log(order);
        $log.log('And Now in JSON....');
        $log.log(JSON.stringify(order));
        $http.post('http://localhost:8080/my.rest.service/apI/Order/addOrder',JSON.stringify(order)).success(function(data){
            $log.log("here's the data:\n");
            $log.log(data);
            $modalInstance.close(data._id.$oid)
        });
    };
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };      
};
myApp.controller('modalCtrl',modalCtrl);

It didn't help. I tried:

>Delete from response header allow(“OPTIONS”). > Remove $httpprovider configuration from the application > change $httpprovider configuration to call myapp Config (function ($httpprovider) {...}), pass the function itself instead of the array

Get requests using the same configuration:

@GET
@Path("/listall/")
@Produces(MediaType.APPLICATION_JSON)
public Response listAll(){
    DB db = mongo.getDB("staffing");
    DBCollection col = db.getCollection("orders");
    List<DBObject> res = col.find().limit(200).toArray();
    return Response.ok()
            .entity(res.toString())
            .header("Access-Control-Allow-Origin",PUT")
            .allow("OPTIONS")
            .build();       
}

This controller works normally:

myApp.controller('orderListCtrl',function ($scope,$http){
    $http.get('http://localhost:8080/my.rest.service/apI/Order/listall').success(function(data) {
        for (var i = 0; i < data.length; i++) {
            if (data[i].description.length > 200) {
                data[i].shortDesc = data[i].description.substring(0,196) + "...";
            } else {
                data[i].shortDesc = data[i].description;
            }
        };
        $scope.orders = data;
    });
});

Update #1:

I tried the same request on the same original basis, basically serving the angular application next to the rest service from locahost: 8080 This configuration is valid, but needs to be changed slightly, and some general cleaning has been done in my code, which I edited above

Postal still failed as a CORS request, but I'm still looking for the missing part of this configuration

Update #2:

I investigated the job request header file and compared it with non - job requests

The work acquisition request returns the following title and its response:

The inoperative request returned a header file with a response, but the access control allow origin header is missing:

I believe this problem has become a problem. Deleting these headers from the response before returning to the client will cause the browser's request to fail

Update #3:

Submit a test post request from Chrome's rest console extension to the same URL and return the corresponding response header, as shown in the screenshot below

At this point, I'm not sure what to delete the title between Jersey and my role client, but I believe it's the culprit

Solution

The cause of the problem is insufficient processing of options requests sent before flight before post requests before using the correct cross origin header

I can solve this problem by downloading and implementing the CORS filter found on this page: http://software.dzhuvinov.com/cors-filter-installation.html.

If you encounter similar problems, please follow the instructions to test to see that your options request no longer fails and the subsequent successful requests

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
***
下一篇>>