使用Aurelia-Fetch-Client

时间:2017-09-29 12:23:46

标签: javascript http typescript aurelia fetch-api

尝试使用fetch API(由Aurelia-fetch-client包装)从响应中检索标头时,headers对象为空;

这是我获取客户的方法

 public GetCustomers(): Promise<CustomerList> {

    let  customerList = new CustomerList();
    return this._http.fetch('/api/customers')
    .then(response => {

        let links = response.headers.get('Link');
        customerList.pagination.pageCount = parseInt(response.headers.get('X-Pagination.pageCount'));
        customerList.pagination.pageNumber = parseInt(response.headers.get('X-Pagination.pageNumber'));
        customerList.pagination.pageSize = parseInt(response.headers.get('X-Pagination.pageSize'));
        customerList.pagination.totalItems = parseInt(response.headers.get('X-Pagination.totalItems'));

       console.log(response.headers);
        return  response.json() as any

    }).then(data =>{          
        data.map(
            item => {
                let customer: Customer = new Customer(this);
                Object.assign(customer, item);
                customerList.customers.push(customer);
            });
            return customerList;  
       });
}

Http Fetch配置

constructor(private eventAggregator: EventAggregator, url: string) {

    this._http = new HttpClient();

    this._http.configure(config => {
        config
            .withBaseUrl(url)
            .withInterceptor({
                request(request) {
                    console.log(`Requesting ${request.method} ${request.url}`);
                    return request; // you can return a modified Request, or you can short-circuit the request by returning a Response
                },
                response(response) {
                    console.log(`Received ${response.status} ${response.url}`);
                    return response; // you can return a modified Response
                }
            })
            .withDefaults({
                'mode' : 'cors',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`

                }
            })
            .useStandardConfiguration();
    });

}

以下是我们在Chrome中可以看到的内容。我正在暴露我想要的标题。

enter image description here

1 个答案:

答案 0 :(得分:0)

据我了解,在服务器上使用CORS策略时,您需要专门选择响应中的标头。 ASP.NET Core有一个&#34; WithExposedHeaders&#34;方法 https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.cors.infrastructure.corspolicybuilder.withexposedheaders?view=aspnetcore-2.0