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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With