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 ?
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.
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