【问题标题】:Angular - creating service to use google url shortenerAngular - 创建服务以使用谷歌网址缩短器
【发布时间】:2018-01-21 16:41:05
【问题描述】:

我正在尝试编写一个使用谷歌网址缩短器的服务,但遇到了问题 以下是我的服务:

  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);
}

来自谷歌 API 的错误:

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

}

API key 没有错误,因为用 angular1 编写的相同代码返回的是 shortUrl

【问题讨论】:

    标签: angular google-url-shortener


    【解决方案1】:

    不确定,但应在 Authorization 标头中提供密钥。

    例子:

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

    【讨论】:

      【解决方案2】:

      苦苦挣扎了一天,用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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-04
        • 1970-01-01
        • 1970-01-01
        • 2013-04-11
        • 1970-01-01
        相关资源
        最近更新 更多