简体   繁体   中英

Headers null when making a CORS request with Aurelia-Fetch-Client

When attempting to retrieve headers from a response using the fetch API(wrapped by the Aurelia-fetch-client) the headers object is empty;

Here's my method to fetch customers

 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 configuration

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();
    });

}

Here's what we can see in Chrome. I'm exposing the headers i want.

在此处输入图片说明

As far as I understand, when using a CORS policy on the server, you need to specifically opt-in to headers in the response. ASP.NET Core has a "WithExposedHeaders" method for this https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.cors.infrastructure.corspolicybuilder.withexposedheaders?view=aspnetcore-2.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM