【发布时间】:2016-03-12 09:26:52
【问题描述】:
我有以下运行良好的代码:
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);
});
但是,如果用 json(auth) 替换 body: JSON.stringify(auth) 行,这是我相信使用 Aurelia JSON 帮助器对对象进行 JSON 序列化的正确方法,我的 API 会抛出一个错误的请求。
helper 与 JSON.stringify 有什么不同吗?
【问题讨论】:
-
您的 API 是否与您的网站在同一个域中?如果是这样,请尝试摆脱配置函数中的绝对路径 (https:// )。我可以看到,由于某种原因,请求正文使用绝对 URL 为空,而如果我发出本地请求,您的示例工作正常......
-
不,API 位于不同的 URL,这实际上给了我一个 CORS 问题,我暂时在 Safari 中禁用了该问题。
-
请运行一个网络代理(例如 fiddler),看看那里到底发生了什么。然后将结果添加到您的问题中。您是否曾经看到过您的 POST 请求,或者可能只是一个使用 OPTIONS 方法的请求?
-
我在上面的代码中遇到 415(不支持的媒体类型)错误,针对 ASP.Net WEB API!
-
@Anj 您很可能遇到了 CORS 问题。使用 OPTIONS 请求,您的浏览器试图确定是否允许将其他请求发送到外部域 developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS