簡體   English   中英

Angular-創建服務以使用Google URL縮短器

[英]Angular - creating service to use google url shortener

我正在嘗試編寫使用google url縮短器的服務,但面臨問題以下是我的服務:

  urlShortener(longUrl: string): Observable<string> {
let body = {longUrl: longUrl}
let options = {
  params: {key: XXXXXX},
};
return this.http.post('https://www.googleapis.com/urlshortener/v1/url', body, options)
  .map(response => {
    console.debug('response',response);
    return response;
  })
  .catch(this.handleError);
}

來自Google API的錯誤:

{
"error": {
 "errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}

}

使用API​​密鑰沒有錯誤,因為用angular1編寫的同一代碼返回shortUrl

不確定,但應在授權標頭中提供密鑰。

例:

let headers = new Headers();
    headers.append("Authorization","Basic YW5ndWxhci13YXJlaG91c2Utc2VydmljZXM6MTIzNDU2");
    this.http.post(AUTHENTICATION_ENDPOINT, null, {headers: headers}).subscribe(response => {
      console.log(response);
    });

經過一天的努力,使用http.request而不是http.post解決了該問題。代碼如下:

let myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');
let myParams = new URLSearchParams();
myParams.append('key', 'XXX-XXXX);

const options = new RequestOptions({
  method: RequestMethod.Post,
  headers: myHeaders,
  params: myParams,
  url: 'https://www.googleapis.com/urlshortener/v1/url',
  body: {longUrl: longUrl}
});
const req = new Request(options);

return this.http.request(req)
  .map(response => {
    console.debug('response', response.json().id);
    return response.json().id;
  })
  .catch(this.handleError);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM