【问题标题】:How to use Google translate node library in angular 4如何在 Angular 4 中使用谷歌翻译节点库
【发布时间】:2018-09-27 18:10:59
【问题描述】:

我想在我的 Angular 4 应用程序中使用谷歌翻译库。我没有看到任何文档。所以我正在研究rest api。使用其余 API,我得到了以下响应。当我在邮递员中使用相同的网址时,它工作正常。

app.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpRequest , HttpHeaders, HttpParams} from '@angular/common/http';

@Injectable()
export class HttpService {

    userData : any;

    constructor(public http: HttpClient) {}

    /*  First parameter is url.
        second is object of request params.
        Don't pass 2nd paramater if not required.
    */
    get<T>(url, requestParams?:Object) {
        let options = {};
        options = this.getOptions(requestParams);
        return this.http.get<T>(url,options);
    }

    /*  First parameter is url.
        second is request body. Pass atleast null if no body for your request.
        Third is request parameters.
        Don't pass 3rd paramater if not required.
    */
    post<T>(url, postBody: any, requsetParams?: Object) {
        let options = {};
        options = this.getOptions(requsetParams);
        return this.http.post<T>(url,postBody, options);
    }

    /*  First parameter is url.
        second is object of request params.
        Don't pass 2nd paramater if not required.
    */
    delete(url, requestParams?: Object) {
        let options = {};
        options = this.getOptions(requestParams);
        return this.http.delete(url, options);
    }

    /*  First parameter is url.
        second is request body. Pass atleast null if no body for your request.
        Third is request parameters.
        Don't pass 3rd paramater if not required.
    */
    put(url, putData, requsetParams?: Object) {
        let options = this.getOptions(requsetParams);
        return this.http.put(url, putData, options);
    }

    getOptions(requestParams?: Object) {

        let options = {};

        this.userData = JSON.parse(localStorage.getItem("currentUser"));
        if(this.userData !== null) {
            let headers = new HttpHeaders({
                'authorization': 'Bearer ' + this.userData.token
            })
            options['headers'] = headers;
        }

        if(requestParams !== undefined) {
            let httpParams = new HttpParams();
            Object.keys(requestParams).forEach(function (key) {
                httpParams = httpParams.append(key, requestParams[key]);
            });

            options['params'] = httpParams;
        }

        return options;
    }

}

我的服务.ts

import { Injectable } from '@angular/core';
import { HttpService } from '../http.service';
import { TranslateResponse } from './model/translate-response';
import { Observable } from 'rxjs/Observable';
import { DetectLanguageResponse } from './model/detect-language-response';

const googleTranlateApiURL: string = 'https://translation.googleapis.com/language/translate/v2';
const googleTranlateApiKey: string = '';
const googleTranlateApiFormat: string = 'text';


@Injectable()
export class GoogleTranslateService {



  constructor(private httpService: HttpService) { }

  translate(q: string, target: string, source: string): Observable<TranslateResponse> {
    return this.httpService.post<TranslateResponse>(`${googleTranlateApiURL}?q=${q}&target=${target}&source=${source}&key=${googleTranlateApiKey}`, {});
  }

  detect(q: string): Observable<DetectLanguageResponse> {
    return this.httpService.post<DetectLanguageResponse>(`${googleTranlateApiURL}/detect?q=${q}&key=${googleTranlateApiKey}`, {});
  }
}

回复

{
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "errors": [
      {
        "message": "Request had invalid authentication credentials.",
        "reason": "authError"
      }
    ],
    "status": "UNAUTHENTICATED"
  }

任何人都可以帮助我做错了什么以及如何在 Angular 4 中使用普通的 nodejs 库

https://cloud.google.com/translate/docs/reference/libraries

【问题讨论】:

  • 一些代码好吗?看起来您没有有效的凭据。您需要展示一些东西,以便人们可以复制它
  • @ChauTran,已更新代码
  • 您似乎没有在 POST 网址中附加 APIKey,因为 googleTranlateApiKey 是一个空字符串?
  • 我删除了发布问题的密钥。我的应用程序中有密钥
  • 您的请求是否有Authorization: Bearer token?该令牌是 API 密钥还是用户的 JWT 令牌?

标签: node.js angular google-translate google-translation-api


【解决方案1】:

问题在于Authorization 标头与请求一起发送到Google Translate API

Google Translate API 将在请求标头中查找Authorization 标头,并从中提取值以用作API Key。拥有Authorization 标头,Google Translate API 将忽略请求 URL 中的 key 查询参数。

您需要对NOT 执行一些逻辑,将POST 上的Authorization 附加到API,或者使用API Key 作为Authorization 标头而不是User's Token

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    相关资源
    最近更新 更多