【问题标题】:Canada Post Rates Error in Ionic Project Response for preflight has invalid HTTP status code 500Canada Post Rates Error in Ionic Project Response for preflight has invalid HTTP status code 500
【发布时间】:2018-11-17 21:04:18
【问题描述】:

我正在处理一个 HTTP 请求,该请求将 POST 请求发送到加拿大邮政 API 以查询运输报价:

getRates(weight: number, originPostal, destPostal) {
    const options = {
      headers: new HttpHeaders({
        'Authorization': 'Basic ' + btoa(this.TEST_USERNAME + ':' + this.TEST_PASSWORD),
        'Accept': 'application/vnd.cpc.ship.rate-v3+xml',
        'Content-Type': 'application/vnd.cpc.ship.rate-v3+xml',
        'Accept-language': 'en-CA',
      }),
    };

    const body = `
    <?xml version="1.0" encoding="utf-8"?>
      <mailing-scenario xmlns="http://www.canadapost.ca/ws/ship/rate-v3">
        <customer-number>${this.TEST_NUMBER}</customer-number>
        <parcel-characteristics>
        <weight>${weight}</weight>
        </parcel-characteristics>
        <origin-postal-code>${originPostal}</origin-postal-code>
        <destination>
          <domestic>
            <postal-code>${destPostal}</postal-code>
          </domestic>
        </destination>
      </mailing-scenario>
    `;

    return this.http.post<any>(this.TEST_URL, body, options)
}

查询在 Postman 上运行良好,但在 Ionic 项目(ionic serveionic run -l)上运行良好。我在网上搜了一下,是CORS issueHttp failure response for (unknown url): 0 Unknown Error,我在下面添加到ionic.config.json文件中

  "proxies": [
    {
      "path": "/price",
      "proxyUrl": "https://ct.soa-gw.canadapost.ca/rs/ship/price"
    }
  ]

API 密钥、URL 由加拿大邮政提供,可在here找到

我遇到的错误:

无法加载https://ct.soa-gw.canadapost.ca/rs/ship/price:响应 预检的 HTTP 状态码 500 无效。

14:32:24.786 shipping.ts:34 {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":null,"ok":false,"name":"HttpErrorResponse","message":"Http failure response for (unknown url): 0 Unknown Error","error":{"isTrusted":true}}

任何帮助将不胜感激!

2018 年 6 月 15 日更新:

我今天在真机上试过了,得到这样的错误:

preflight response issue with ionic3 app on ios build only [ resolved ]Ionic UIWebView,不幸的是,请求仍然得到同样的错误......

【问题讨论】:

  • 您可能希望在浏览器中添加一个扩展,以便从本地计算机进行测试:chrome.google.com/webstore/detail/allow-control-allow-origi/…
  • @DaleNguyen 我试过了,但没有成功
  • 在您的设备上试用。这可能只是一个浏览器问题。
  • @Ari 我在真正的IOS设备上试过了,没有运气...
  • @haifzhan:chrome 扩展在过去帮助了我,但我有一个案例,我无法让它在设备上运行。解决此问题的一种方法是拥有一个轮询 API 并存储数据的服务器。然后让您的客户端从您的服务器获取数据,而不是直接从 API 获取数据。

标签: angular ionic-framework ionic3


【解决方案1】:
getRates(weight: number, originPostal, destPostal) {
    this.http.setDataSerializer('utf8');
    return this.http
      .post(
        this.URL,
        this.body(weight, originPostal, destPostal),
        this.headers(this.USER_NAME, this.PASSWORD)
      );
  }

  private headers(username, password) {
    return {
      'Authorization': 'Basic ' + btoa(username + ':' + password),
      'Accept': 'application/vnd.cpc.ship.rate-v3+xml',
      'Content-Type': 'application/vnd.cpc.ship.rate-v3+xml;',
      'Accept-language': 'en-CA'
    };
  }

  private body(weight, originPostal, destPostal) {
    return `<?xml version="1.0" encoding="utf-8"?>
    <mailing-scenario xmlns="http://www.canadapost.ca/ws/ship/rate-v3">
    <customer-number>MY_CUSTOMER_NUMBER</customer-number>
      <parcel-characteristics>
        <weight>${weight}</weight>
      </parcel-characteristics>
      <origin-postal-code>${originPostal}</origin-postal-code>
        <destination>
          <domestic>
            <postal-code>${destPostal}</postal-code>
          </domestic>
        </destination>
    </mailing-scenario>`;
  }

有几个问题导致请求不起作用:

  1. ionic 中的 HttpClient 模块(Angular 模块)总是有 CORS,ionic 团队有相关的 FAQ。在我的情况下,我使用 firebase 作为后端,因此不经常使用 http,我决定切换到 Ionic Native Http
  2. XML问题,标签&lt;?xml&gt;前有一个空格,直到打印出错误消息详细信息才意识到(错误消息本身也是XML格式,其余省略,因此一开始我以为只有Server报错信息,我把整条信息剪成小块打印到控制台后,发现是非法的xml格式,然后我发现有一个前导空格):

将 XML 转换为 JSON(xml2js 让生活更轻松):

import * as xml2js from 'xml2js';

this.rateProvider.getRates(this.totalWeight, this.ORIGINAL_POSTAL_CODE, this.selectedAddress.postalCode.toUpperCase())
  .then(resp => {
    xml2js.parseString(resp.data, (err, jsonResp) => {
      this.quotes = this.extractQuotes(jsonResp);
      this.presentActionSheet(this.quotes);
      this.isSelected = false;
    });
  })
  .catch(error => {
    console.log(error);
  });

最后,让它工作:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 2022-12-27
    • 2022-01-08
    • 2022-12-27
    • 2017-12-31
    • 1970-01-01
    相关资源
    最近更新 更多