3

I have been looking for 5 hours or so but i give up. my ajax get request just does't want to work.

var ApiResponce = $.ajax({
    url: "http://localhost:18428/api/Reservation/" + userid + "?weekNumber=" + weeknr,
    type: 'GET',
    headers: {
        'Authorization': "bearer " + token,  
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Credentials': true,
    },
    dataType: 'json',
    crossDomain: true,
    contentType: "application/json",

    success: function(responce) {
        console.log("success");
        console.log(responce);
    },
    error: function(err) {
      console.log("error");
        console.log(ApiResponce);
    },
});

it connecting to a standard C# mvc api but all that i am getting is this error:

XMLHttpRequest cannot load http://localhost:18428/api/Reservation/1?weekNumber=1. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 405.

Nick Assink
  • 33
  • 1
  • 1
  • 4
  • Might be duplicate of this http://stackoverflow.com/questions/35588699/response-to-preflight-request-doesnt-pass-access-control-check-angularjs – aggaton Jan 05 '17 at 00:06
  • Why did i not think of that? only why do i get this error now? XMLHttpRequest cannot load http://localhost:18428/api/Reservation/1?weekNumber=1. Response for preflight has invalid HTTP status code 405 – Nick Assink Jan 05 '17 at 00:31

1 Answers1

2

If you're using Apache Tomcat in server side you need to edit your web.xml file on your servlet container and add the following lines:

     <filter>
        <filter-name>CorsFilter</filter-name>
        <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
        <init-param>
                <param-name>cors.allowed.origins</param-name>
                <param-value>*</param-value>
        </init-param>
        <init-param>
                <param-name>cors.allowed.methods</param-name>
                <param-value>GET, HEAD, POST, PUT, DELETE, OPTIONS</param-value>
        </init-param>
        <init-param>
                <param-name>cors.exposed.headers</param-name>
                <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials,X-Bonita-API-Token</param-value>
        </init-param>
        <init-param>
                <param-name>cors.allowed.headers</param-name>
                <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,X-Bonita-API-Token</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Note: Works in Apache Tomcat 7+, Don't forget restart tomcat.