我有以下Web服务器方法,该方法将数据返回到我们的前端应用程序。
[FunctionName("SearchCustomerBySearchTerm")]
public static async Task<HttpResponseMessage> SearchCustomerBySearchTerm([HttpTrigger(AuthorizationLevel.Function, WebRequestMethods.Http.Get, Route = "Customer/SearchCustomerBySearchTerm/{searchTerm}/pageSize/{pageSize}")]HttpRequestMessage req, TraceWriter log, string searchTerm, int pageSize)
{
try
{
var continuationToken = req.Headers.TryGetValues("continuationToken", out IEnumerable<string> values) ? values.FirstOrDefault() : null;
PagedResponse<CustomerSearchResult> pagedResponse = await _customerComponent.FindCustomerBy(searchTerm, continuationToken, pageSize);
if (pagedResponse == null) return req.CreateResponse(HttpStatusCode.NoContent, $"Could not find any data related to {searchTerm}");
HttpResponseMessage responseMessage = req.CreateResponse(HttpStatusCode.OK, pagedResponse.Results);
responseMessage.Content.Headers.Add("continuationToken", pagedResponse.Continuation);
responseMessage.Content.Headers.Add("Access-Control-Expose-Headers", "*");
return responseMessage;
}
catch (Exception ex)
{
log.Error(ex.Message);
return req.CreateResponse(HttpStatusCode.InternalServerError, "Something went wrong. Could not search for customers");
}
}
通过添加Access-Control-Expose-Headers
,允许公开所有标题。
我正在从Angular应用程序中进行以下请求:
searchCustomersPaged(searchTerm: string, continuationToken: string): Observable<HttpResponse<CustomerSearchResult>> {
let customHeaders = new HttpHeaders().set("continuationToken", this.currentContinuationToken);
const url = "http://localhost:7071/api/Customer/SearchCustomerBySearchTerm/andrew/pageSize/10";
const parsedUrl = encodeURI(url);
return this.http.get<HttpResponse<CustomerSearchResult>>(parsedUrl, { headers: customHeaders });
}
正如您在上面看到的那样,我希望有一个HttpResponse<CustomerSearch>
回来。
这是我尝试阅读标题的方法:
nextClikcedHandle(continuationToken: string): void {
this.customerService.searchCustomersPaged(this.customerService.searchTerm, this.currentContinuationToken)
.subscribe(resp => {
//add current continuation token, to previous now, as this will be used for 'previous' searching
this.previousContinuationTokens.push(this.currentContinuationToken);
//set next continuation token received by server
this.currentContinuationToken = resp.headers.get('continuationToken');
//return search results
this.customerService.searchResults.next(resp.body);
});
}
使用以上代码,resp.headers
和resp.body
始终为undefined
。为什么会这样?
如果我查看Chrome中的Network
标签,则可以看到返回的数据以及标题。
我在做什么错了?
答案 0 :(得分:0)
我找到了一篇有用的文章here:
默认情况下,HttpClient返回响应的主体。您可以 将观察键设置为“响应”值的对象传递给 得到完整的回应。这对于检查某些 标头:
因此,我使用添加的var $table = $('table').tablesorter({
theme: 'blue',
widgets: ['zebra', 'columns']
}),
// column index
index = 0,
// column data to add to the table
columns = ['firstName', 'lastName', 'phone|format', 'streetAddress',
'email', 'city', 'usState|abbr'];
$('button').click(function () {
var url = "http://www.filltext.com/?callback=?";
$.getJSON(url, {
'rows': 10, // number of rows in the table
'data': '{' + columns[index] + '}'
})
.done(function (data) {
// add new header cell
$table.find('thead tr').append('<th>' + columns[index].split('|')[0] + '</th>');
// increment index to next column
index = (index + 1) % columns.length;
// add new cell to each tbody row
$.each(data, function (i, item) {
var html = "<td>" + item.data + "</td>";
$table.find('tbody tr').eq(i).append(html);
});
// update cache
$table.trigger('updateAll');
});
});
键如下更改了代码。
observe
更改上述方法后,我可以按常规查询正文和标头:
searchCustomersPaged(searchTerm: string, continuationToken: string): Observable<HttpResponse<CustomerSearchResult>> {
let customHeaders = new HttpHeaders().set("continuationToken", this.currentContinuationToken);
const url = "http://localhost:7071/api/Customer/SearchCustomerBySearchTerm/andrew/pageSize/10";
const parsedUrl = encodeURI(url);
return this.http.get<CustomerSearchResult>(parsedUrl, { headers: customHeaders, observe: 'response' });
}