1

I'm trying to post request with JSON body using aurelia fetch client. Here is my code:

import {inject, NewInstance} from 'aurelia-framework';
import {HttpClient, json} from 'aurelia-fetch-client';

@inject(NewInstance.of(HttpClient))
export class TestClass {
  constructor(httpClient) {
    this.__httpClient = httpClient.configure(x => {
        x.useStandardConfiguration()
        .withBaseUrl('http://test.com/api/')
    });
  }

  sendRequest() {
    let test= {
      paramone: 'One',
      paramtwo: 'Two'
    };
    this.__httpClient.fetch('postdata', {
      method: 'post',
      body: json(test)
    });
  }    
}

However I get the following error in browser console:

Fetch API cannot load http://test.com/api/postdata. Response for preflight has invalid HTTP status code 404

The problem is that if I don't send json body (i.e. body: '') the request reaches the server! So, there's some issue with the body. Could you please help me to find out the root cause?

sleb
  • 193
  • 1
  • 12
  • If you send without the body - does the request still perform the preflight check? – Tom Mar 21 '17 at 10:20
  • I'm not sure how can I check this. Right now I tried to post request with aurelia-http-client, but I get the very similar error if I send request with json body: XMLHttpRequest cannot load http://test.com/api/postdata. Response for preflight has invalid HTTP status code 404 bluebird.js:1542 Unhandled rejection (<{"requestMessage":{"method":"POST","ur...>, no stack trace) – sleb Mar 21 '17 at 11:32
  • You said if you don't send JSON body the request reaches the server. When you do this, is there a preflight (`OPTIONS`) request? You'll see it in the Network Panel of Chrome's inspect tool if there is. Not all servers are set up to handle preflight `OPTIONS` requests - and can return a 404 if they're not. – Tom Mar 21 '17 at 11:34
  • 1
    Yes, I see OPTIONS in console only when I send request with body. It seems that preflight check is always performed when json data is sent with "application/json" stated as Content-Type. For now I solved the issue with sending data as "application/x-www-form-urlencoded" ("text/plain" also do the job). It seems that we can't use "application/json" with aurelia for CORS. – sleb Mar 21 '17 at 11:44
  • CORS is the issue. I'd suggest using `application/x-www-form-urlencoded` isn't a permanent solution though. Ideally the API should have enabled CORS. – Tom Mar 21 '17 at 11:46
  • @thebluefox is correct - it's definitely a CORS issue. I've come across this issue recently, when the Aurelia application is served from a different location to the API, then the API needs to have CORS enabled. You need to explicitly set the Origin (where you're getting your Aurelia App from) as allowed in the API configuration – ry8806 Mar 22 '17 at 09:12

0 Answers0