AngularJS : Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

匿名 (未验证) 提交于 2019-12-03 01:55:01

问题:

here is my code :

angular.module('option')     .factory('optionListService', ['$resource', function($resource) {     return $resource(HOST+'option/action/:id', {}, {         'get':    {method:'GET'},             'save':   {method:'POST'},             'query':  {method:'GET', isArray:true},             'remove': {method:'DELETE'},             'delete': {method:'DELETE'}     });     }]); 

and this work for GET requests and not for POST !

I'm using Apache as a server and configured it with :

         Order Allow,Deny         Allow from all      Header set Access-Control-Allow-Origin "*" 

and in my angularjs I include in config of module app:

delete $httpProvider.defaults.headers.common['X-Requested-With']; delete $httpProvider.defaults.headers.post['Content-type']; 

but the request POST still not working !!

I hope that someone can give any idea.

回答1:

Add those headers on the server side:

Access-Control-Request-Headers: X-Requested-With, accept, content-type Access-Control-Allow-Methods: GET, POST 

If still not working post the details of the preflight OPTIONS request which the browser is sending.

Why is this required?

If it is not a simple request (e.g. GET or POST of form data) the browser sends a preflight HTTP OPTIONSrequest to the server to check if CORS is allowed. This request contains some Access-Control-Request headers (can differ based on the specific request):

Access-Control-Request-Headers: accept, content-type Access-Control-Request-Method: POST 

Now it is important that the server references the same Access-Control-Allow header in the response:

Access-Control-Allow-Headers: accept, content-type Access-Control-Allow-Methods: POST Access-Control-Allow-Origin: * 

Otherwise the request is rejected by the browser.

@ilyas : finaly after 3hours of reseach I sovelved this problem

//Part added by ilyas :     if (isset($_SERVER['HTTP_ORIGIN'])) {         header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");         header('Access-Control-Allow-Credentials: true');         header('Access-Control-Max-Age: 86400');    // cache for 1 day     } //End of part. 

I hope this help others.



回答2:

Add Header into your file which you hitting from ajax call as follows

 php header('Access-Control-Allow-Origin: *'); ?> 


回答3:

I found great example and explanation here http://www.codingpedia.org/ama/how-to-add-cors-support-on-the-server-side-in-java-with-jersey/

@GET @Path("{id}") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Response getPodcastById(@PathParam("id") Long id,     @QueryParam("detailed") boolean detailed)         throws IOException, AppException {     Podcast podcastById = podcastService.getPodcastById(id);     return Response.ok() //200             .entity(podcastById, detailed ? new Annotation[]        {PodcastDetailedView.Factory.get()} : new Annotation[0])             .header("Access-Control-Allow-Origin", "*")             .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")                 .allow("OPTIONS").build(); } 


回答4:

Here is a problem on server side. If your application is using spring framework. You can fix it by using the filter method

@Override     protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException {         res.setHeader("Access-Control-Allow-Origin", "*");         res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");         res.setHeader("Access-Control-Max-Age", "3600");         res.setHeader("Access-Control-Allow-Headers", "X-PINGOTHER,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");         res.addHeader("Access-Control-Expose-Headers", "xsrf-token");         if ("OPTIONS".equals(req.getMethod())) {          res.setStatus(HttpServletResponse.SC_OK);         } else {           chain.doFilter(req, res);         }             } 

By the way, you can dig deeper it via post angularjs spring cross-origin request blocked



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!