4

我一直在努力反对 fetch-client 太久了,我需要一些帮助。

我正在从 Skyscanner 获取一些数据。该请求到达他们的 API,Chrome 的开发工具将其作为完整的获取请求在网络选项卡中列出,代码为 200 和正确的响应正文。

import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
@inject(HttpClient)
export class Flights {
    constructor(http){
        http.configure(config => {
          config
            .withBaseUrl('http://partners.api.skyscanner.net/apiservices/')
            .withDefaults({
                mode: 'no-cors',
                headers: {
                    'Accept': 'application/json',
                    'Content-type' : 'application/json'
                }
            });
        });

        this.data = "";
        this.http = http;
    }
  activate() {
    this.http.fetch('browsequotes/v1.0/GB/GBP/en-GB/UK/anywhere/anytime/anytime?apiKey=MYAPIKEYGOESHERE')
            .then(response => {
                console.log(response);
                console.log(response.response);
                console.log(response.content);
                console.log(response.data);
            })
            .catch(ex => {
                console.log(ex);
            }); 
  }
}

但是当打印响应对象时,它没有任何内容:

Response {}
  body: null
  bodyUsed: false
  headers: Headers
  __proto__: Headers
  ok: false
  status: 0
  statusText: ""
  type: "opaque"
  url: ""
  __proto__: Response

所有剩余的 console.log 都产生undefined

我是否错误地使用了 fetch-client?我错过了什么?

4

2 回答 2

3

请注意,您收到了一个不透明的响应( type: "opaque")。不透明的响应不允许您阅读它们。这是由于no-cors您之前设置的模式。您应该使用该cors模式,SkyScanner 应该为您的 API 密钥提供正确的标头,这是我认为他们不会做的事情。

于 2016-02-08T10:38:54.157 回答
0

我解决了我的问题,该问题可能属于同一标题,所以在这里留下答案,因为我在网上找不到任何东西。可能是我只是愚蠢,但我以前这样做过......

.then(response => {response.json()})
.then(data => console.log(data))

把我的头撞了一天,结果发现解决方法是:

.then(response => response.json())
.then(data => console.log(data))

或者

.then(response => { return response.json()})
.then(data => console.log(data))

真的很简单,与 Aurelia 或 Fetch 无关,但对 Javascript 语法的理解。

于 2017-10-31T07:08:56.297 回答