Нулевые заголовки при выполнении запроса CORS с помощью Aurelia-Fetch-Client

При попытке получить заголовки из ответа с использованием API-интерфейса выборки (обернутого клиентом Aurelia-fetch-client) объект заголовков пуст;

Вот мой метод привлечения клиентов

 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-загрузки

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. Я выставляю заголовки, которые хочу.

введите здесь описание изображения


person MrBliz    schedule 29.09.2017    source источник
comment
Вы вообще можете видеть какие-либо заголовки из вашего ответа?   -  person Tom    schedule 29.09.2017
comment
Никто. В сеансе отладки Chrome заголовки являются пустым объектом.   -  person MrBliz    schedule 29.09.2017
comment
Я только что проверил, и я получаю то же самое. Если вместо этого вы используете стандартный aurelia-http-client, то, я подозреваю, вы сможете их увидеть. Но в нем могут отсутствовать другие функции, которые вам нужны.   -  person Tom    schedule 29.09.2017
comment
Ура, я дам ему удар. Звучит как потенциальная ошибка тогда?   -  person MrBliz    schedule 29.09.2017
comment
@MrBliz - найти ответ?   -  person InquisitorJax    schedule 15.02.2018
comment
@InquisitorJax Я не могу вспомнить, знал ли я или нашел обходной путь. Я сейчас в другой компании, так что не могу проверить.   -  person MrBliz    schedule 21.02.2018


Ответы (1)


Насколько я понимаю, при использовании политики CORS на сервере вам нужно специально подписаться на заголовки в ответе. В ASP.NET Core есть метод WithExposedHeaders для этого https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.cors.infrastructure.corspolicybuilder.withexposedheaders?view=aspnetcore.-2.0

person InquisitorJax    schedule 15.02.2018