代码之家  ›  专栏  ›  技术社区  ›  Varun Sukheja

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

  •  0
  • Varun Sukheja  · 技术社区  · 8 年前

    我正在尝试编写一个使用谷歌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

    2 回复  |  直到 8 年前
        1
  •  0
  •   Rohit.007    8 年前

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

    例子:

    let headers = new Headers();
        headers.append("Authorization","Basic YW5ndWxhci13YXJlaG91c2Utc2VydmljZXM6MTIzNDU2");
        this.http.post(AUTHENTICATION_ENDPOINT, null, {headers: headers}).subscribe(response => {
          console.log(response);
        });
    
        2
  •  0
  •   Varun Sukheja    8 年前

    挣扎了一天后,用http解决了这个问题。请求而不是使用http。邮递 代码如下:

    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);
    
    推荐文章