【问题标题】:Aurelia aurelia-fetch-client and with JSON POSTAurelia aurelia-fetch-client 和 JSON POST
【发布时间】: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

标签: json aurelia stringify


【解决方案1】:

json 函数调用 JSON.stringify,但也将Content-Type: application/json 添加到标头。我想知道为您引发的错误是否可能是由于您明确添加标头已经存在。

再次尝试使用json,但这次删除修改标头以添加该 Content-Type 的代码。

有关该 json 函数的代码,请参见此处:https://github.com/aurelia/fetch-client/blob/master/src/util.js

【讨论】:

    猜你喜欢
    • 2017-12-17
    • 2017-05-11
    • 2016-10-22
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多