Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aurelia aurelia-fetch-client and with JSON POST

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 ?

like image 810
user1513388 Avatar asked Dec 07 '15 17:12

user1513388


1 Answers

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.

like image 61
Todd Price Avatar answered Jan 03 '23 13:01

Todd Price