Aurelia aurelia-fetch-client and with JSON POST

user1513388 picture user1513388 · Dec 7, 2015 · Viewed 8.5k times · Source

I have the following code which works is working well:

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


@inject(HttpClient)
export class Items {
  heading = 'Items';
  apiKey = "";

  constructor(http) {
    http.configure(config => {
      config
        .useStandardConfiguration()
        .withBaseUrl('https://testme.com/api/')
          .withDefaults({
            headers: {
              'content-type': 'application/json',
              'Accept': 'application/json',
              'X-Requested-With': 'Fetch'
            }
          })
    });

    this.http = http;
  }

attach() {

let auth = {
  Username:"admin",
  Password:"1234"
};

return this.http.fetch('auth', {
      method: 'post',
      body: JSON.stringify(auth),
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    })
    .then(response => response.json())
    .then(response => {
      this.apiKey = response.APIKey;
      console.log(response);
});

However, if replace the body: JSON.stringify(auth) line with json(auth) which is I believe the correct way to JSON serialise an object using the Aurelia JSON helper, my API throws a bad request.

Is there anything different that the helper does vs JSON.stringify ?

Answer

Todd Price picture Todd Price · Dec 11, 2015

The json function calls JSON.stringify, but also adds Content-Type: application/json to the headers. I'm wondering if the error that's thrown for you might be due to the header already existing since you're explicitly adding it.

Try using json again, but this time remove your code that modifies the headers to add that Content-Type.

See here for the code for that json function: https://github.com/aurelia/fetch-client/blob/master/src/util.js