Angular - 创建使用google url shortener的服务

时间:2018-01-20 14:18:13

标签: angular google-url-shortener

我正在尝试使用google url shortener编写服务,但面临问题 以下是我的服务:

  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

2 个答案:

答案 0 :(得分:0)

不确定,但应在授权标题中提供密钥。

示例:

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

答案 1 :(得分:0)

在争吵一天之后,使用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);