2

I'm using Aurelia Fetch Client to query my own Slim Framework RESTful API. The API includes the correct header (as verified by Postman):

Access-Control-Allow-Headers →X-Requested-With, Content-Type, Accept, Origin, Authorization
Access-Control-Allow-Methods →GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin →*
Cache-Control →no-store, no-cache, must-revalidate, post-check=0, pre-    check=0
Connection →close
Content-Type →application/json;charset=utf-8
Expires →Thu, 19 Nov 1981 08:52:00 GMT
Host →localhost:8080
Pragma →no-cache
X-Powered-By →PHP/5.6.19

However, I'm getting the following error in the Javascript console:

Fetch API cannot load http://localhost:8080/api/v1/calendar/2. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

If I use the CORS extension for Google Chrome, I can connect successfully. (However, a secondary problem is that the CORS extension seems to be killing the response status code, changing everything to 200 even when my API returns 403 or 500.)

My Aurelia code is:

saveCalendar() {
    this.httpClient.fetch('http://localhost:8080/api/v1/calendar/2', {
        method: 'post',
        body: json(data)
    }).then(response => {
            window.alert("Got a response: " + response.status);
            if (response.status == 200) { // OK
                window.alert("Calendar saved!");
            } else { // Error
                window.alert("Error");
            }
        });
    this.getCalendars();
}

Why isn't Access-Control-Allow-Origin: * allowing me access from anywhere?

=== Edit:

After more careful observation, I see that Aurelia and Fetch are making 2 requests. The preflight request OPTIONS seems to go fine and receives the CORS Access-Control-Allow-Origin: * header in the response. However, in the actual POST request, the API is not returning anything. The POST request headers are as follows:

Accept:*/* Accept-Encoding:gzip, deflate, br Accept-Language:en-US,en;q=0.8,es-419;q=0.6,es;q=0.4,gl;q=0.2 Cache-Control:no-cache Connection:keep-alive Content-Length:142 content-type:application/json Host:localhost:8080 Origin:http://localhost:9000 Pragma:no-cache Referer:http://localhost:9000/ User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.59 Safari/537.36

When I copy these headers into Postman to make the same request, it also fails in the same way. But, if I remove one of the headers (content-type:application/json), it works.

The actual request in my Aurelia code looks like this:

// src/common/api.js
import { inject } from 'aurelia-dependency-injection';
import 'fetch';
import { HttpClient, json } from 'aurelia-fetch-client';

@inject(HttpClient)
export class API {
  constructor(httpClient) {
    httpClient.configure(config => {
      config
        .withBaseUrl('http://localhost:8080/api/v1');
        .withDefaults({
          mode: 'cors',
          headers: {
            'Accept': 'application/json'
            'Content-type' : 'application/json'
          }
        });
    });
    this.httpClient = httpClient;
  }

  getData(url) {
    return this.httpClient.fetch(url)
      .then(response => response.json());
  }

  postData(url, data) {
    return this.httpClient.fetch(url, {
      method: 'post',
      body: json(data)
    });
  }
}

It would seem obvious to remove the 'Content-type' : 'application/json' from the Aurelia API client Fetch config, but even when I do, it still sends the header.

So my new questions are: 1. How do I prevent Aurelia from sending this header? 2. OR... Why is Slim dying when receiving this header? 3. Is there anything else wrong with my code?

LStarky
  • 2,740
  • 1
  • 17
  • 47
  • Your local host server on 8080 is running on what? Apache, nginx, IIS, Express? That need a bitch clarification. Thanks! – Marc-Andre R. Oct 20 '16 at 19:31
  • 1
    "as verified by Postman" — Try verifying it with the Network tab of your browser's Developer Tools. I'm guessing you are tripping over the preflight OPTIONS request. – Quentin Oct 20 '16 at 19:37
  • @Marc-AndreR. I'm running the Slim server on PHP's internal server: `php -S localhost:8080 -t public public/index.php` – LStarky Oct 20 '16 at 22:22
  • @LStarky Thanks for precision. Maybe this could help you : http://stackoverflow.com/questions/18382740/cors-not-working-php . Keep me post I'll update my answer if it works for you. By the way, have you seen the link I added to my answer? – Marc-Andre R. Oct 21 '16 at 19:35
  • Sorry about the delay... I'll be working on this on Monday since I didn't have a chance today. – LStarky Oct 21 '16 at 21:58
  • Okay, I've been working on this more. I have determined that the OPTIONS preflight request is working fine with the API, but for some reason one of the headers being included in the POST request from Aurelia to Slim is preventing the API from working correctly: `content-type:application/json`. If I put all the headers in Postman, it fails, but when I remove this header, it works. – LStarky Oct 22 '16 at 12:52

1 Answers1

2

Most likely, your server running on 8080 need to be configured to accept CORS request whether the headerd seems to say otherwise...

The configuration for the said server depends on what you're running that server. I'll update that answer once you clarify this point.

I don't know about the extension you mention, that must do some weird stuff which could end you having more trouble at the end, but that's only my opinion.

You might also want to have a look here : Aurelia Post with http-fetch-client producing an options request

Community
  • 1
  • 1
Marc-Andre R.
  • 658
  • 7
  • 23
  • 1
    This was very helpful information and has helped me with the troubleshooting to find the real error in my Slim code. – LStarky Oct 22 '16 at 14:10
  • @LStarky Glad it help you! Just to clarify so I can edit my post with proper informations, does the link I leaved as comment on you question is what helped you out? Or if it's the link of this post here. Once I have that, I'll edit my post for future people who might needs it too. – Marc-Andre R. Oct 22 '16 at 18:12
  • It was actually not specifically either of the links that addressed my specific problem, but rather the advice to watch the Network tab of the developer tools and look at the request and response headers for each call to my API. I was able to use those in Postman and find the problem with my API. – LStarky Oct 23 '16 at 02:43