18

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 :

<Limit GET HEAD POST PUT DELETE OPTIONS>
        Order Allow,Deny
        Allow from all
    </Limit>
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.

Mimouni
  • 3,564
  • 3
  • 28
  • 37
  • What is the server reply-message? – JoakimB May 14 '14 at 21:08
  • the reply : Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8388/option/save/1. This can be fixed by moving the resource to the same domain or enabling CORS. – Mimouni May 14 '14 at 21:10
  • 2
    This is the server replying that it wont allow your request. You need to look over your server configuration. – JoakimB May 14 '14 at 21:17

4 Answers4

26

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.

Mimouni
  • 3,564
  • 3
  • 28
  • 37
Sebastian
  • 16,813
  • 4
  • 49
  • 56
3

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

<? php header('Access-Control-Allow-Origin: *'); ?>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
dsk
  • 615
  • 1
  • 7
  • 19
1

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();
}
Augustas
  • 1,167
  • 21
  • 31
1

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

David Pham
  • 1,673
  • 19
  • 17