我有以下代码可以正常运行:
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);
});
但是,如果用body: JSON.stringify(auth)
替换json(auth)
行,我相信JSON使用Aurelia JSON帮助程序序列化对象的正确方法,我的API会抛出错误的请求。
帮助器与JSON.stringify有什么不同吗?
答案 0 :(得分:5)
json
函数调用JSON.stringify,但也将Content-Type: application/json
添加到标头中。我想知道为您抛出的错误是否可能是由于您已经存在的标头,因为您已明确添加它。
再次尝试使用json
,但这次删除修改标题的代码以添加Content-Type。
请参阅此处了解该json函数的代码:https://github.com/aurelia/fetch-client/blob/master/src/util.js