使用POSTMAN从Bing Api获取数据时工作正常。
但角度不一样,问题在于发送标题。
错误响应:401(拒绝访问)
这里做错了什么
import { HttpClient, HttpHeaders } from '@angular/common/http';
export class BingSearchComponent implements OnInit {
constructor(private http: HttpClient) { }
doSearch(input) {
console.log(input.value)
let subscriptionKey = 'XXXXXXXX';
let customConfigId = 'XXXXXXXX';
let searchTerm = 'microsoft';
let headers = new HttpHeaders();
let other_header =
headers.append('Ocp-Apim-Subscription-Key','XXXXXXXX'); //prints correctly here
console.log(other_header.get('Ocp-Apim-Subscription-Key'))
let url = 'https://api.cognitive.microsoft.com/bingcustomsearch/v7.0/search?'
+ 'q=' + searchTerm + '&customconfig=' + customConfigId
this.http.get(url, {headers: other_header}).subscribe(
res => console.log('handle your response', res),
msg => console.error(`Error: ${msg.status} ${msg.statusText}`)
);
}
}
答案 0 :(得分:0)
HttpHeaders()是一个不可变列表。
此时:
this.http.get(url, {headers: headers})
标头只设置为new HttpHeaders();
你的意思是把other_header放在头上吗?
答案 1 :(得分:0)
HttpHeader
calss的实例是不可变的,因此调用其方法将返回一个新实例。
你应该尝试一下,(将所有headers
作为对象传递)
http.get('someurl',{headers: {'Ocp-Apim-Subscription-Key':'XXXXXXXX'}});