您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

快速入门:使用文本翻译 API 通过 Node.js 对文本进行直译Quickstart: Use the Translator Text API to transliterate text with Node.js

本快速入门介绍如何使用 Node.js 和文本翻译 REST API 将文本从一个脚本直译(转换)为另一个脚本。In this quickstart, you'll learn how to transliterate (convert) text from one script to another using Node.js and the Translator Text REST API. 在提供的示例中,日语在经过直译后使用拉丁字母。In the sample provided, Japanese is transliterated to use the Latin alphabet.

此快速入门需要包含文本翻译资源的 Azure 认知服务帐户This quickstart requires an Azure Cognitive Services account with a Translator Text resource. 如果没有帐户,可以使用免费试用版获取订阅密钥。If you don't have an account, you can use the free trial to get a subscription key.

先决条件Prerequisites

本快速入门需要:This quickstart requires:

创建一个项目并导入必需的模块Create a project and import required modules

使用你喜欢的 IDE 或编辑器创建一个新项目,或者在桌面上创建一个包含名为 translate-text.js 的文件的新文件夹。Create a new project using your favorite IDE or editor, or a new folder with a file named translate-text.js on your desktop. 然后将以下代码片段复制到项目/文件中:Then copy this code snippet into your project/file:

const request = require('request');
const uuidv4 = require('uuid/v4');

备注

如果尚未使用这些模块,则需在运行程序之前安装它们。If you haven't used these modules you'll need to install them before running your program. 若要安装这些包,请运行 npm install request uuidv4To install these packages, run: npm install request uuidv4.

若要构造 HTTP 请求以及为 'X-ClientTraceId' 标头创建唯一标识符,必须使用这些模块。These modules are required to construct the HTTP request, and create a unique identifier for the 'X-ClientTraceId' header.

设置订阅密钥Set the subscription key

此代码会尝试从环境变量 TRANSLATOR_TEXT_KEY 读取文本翻译订阅密钥。This code will try to read your Translator Text subscription key from the environment variable TRANSLATOR_TEXT_KEY. 如果不熟悉环境变量,则可将 subscriptionKey 设置为字符串并注释掉条件语句。If you're not familiar with environment variables, you can set subscriptionKey as a string and comment out the conditional statement.

将以下代码复制到项目中:Copy this code into your project:

/* Checks to see if the subscription key is available
as an environment variable. If you are setting your subscription key as a
string, then comment these lines out.

If you want to set your subscription key as a string, replace the value for
the Ocp-Apim-Subscription-Key header as a string. */
const subscriptionKey = process.env.TRANSLATOR_TEXT_KEY;
if (!subscriptionKey) {
  throw new Error('Environment variable for your subscription key is not set.')
};

配置请求Configure the request

使用通过请求模块提供的 request() 方法,可以以 options 对象的形式传递 HTTP 方法、URL、请求参数、标头和 JSON 正文。The request() method, made available through the request module, allows us to pass the HTTP method, URL, request params, headers, and the JSON body as an options object. 在此代码片段中,我们将配置请求:In this code snippet, we'll configure the request:

备注

有关终结点、路由和请求参数的详细信息,请参阅文本翻译 API 3.0:直译For more information about endpoints, routes, and request parameters, see Translator Text API 3.0: Transliterate.

let options = {
    method: 'POST',
    baseUrl: 'https://api.cognitive.microsofttranslator.com/',
    url: 'transliterate',
    qs: {
      'api-version': '3.0',
      'language': 'ja',
      'fromScript': 'jpan',
      'toScript': 'latn'
    },
    headers: {
      'Ocp-Apim-Subscription-Key': subscriptionKey,
      'Content-type': 'application/json',
      'X-ClientTraceId': uuidv4().toString()
    },
    body: [{
          'text': 'こんにちは'
    }],
    json: true,
};

AuthenticationAuthentication

若要对请求进行身份验证,最容易的方法是将订阅密钥作为 Ocp-Apim-Subscription-Key 标头传入,这是我们在此示例中使用的方法。The easiest way to authenticate a request is to pass in your subscription key as an Ocp-Apim-Subscription-Key header, which is what we use in this sample. 替代方法是交换订阅密钥来获取访问令牌,将访问令牌作为 Authorization 标头传入,以便对请求进行验证。As an alternative, you can exchange your subscription key for an access token, and pass the access token along as an Authorization header to validate your request. 有关详细信息,请参阅身份验证For more information, see Authentication.

发出请求并输出响应Make the request and print the response

接下来,请使用 request() 方法来创建请求。Next, we'll create the request using the request() method. 它采用我们在上一部分创建的 options 对象作为第一个参数,然后输出美化的 JSON 响应。It takes the options object that we created in the previous section as the first argument, then prints the prettified JSON response.

request(options, function(err, res, body){
    console.log(JSON.stringify(body, null, 4));
});

备注

在此示例中,我们将在 options 对象中定义 HTTP 请求。In this sample, we're defining the HTTP request in the options object. 不过,请求模块也支持便捷方法,例如 .post.getHowever, the request module also supports convenience methods, like .post and .get. 有关详细信息,请参阅便捷方法For more information, see convenience methods.

将其放在一起Put it all together

就是这样,你已构建了一个简单的程序。该程序可以调用文本翻译 API 并返回 JSON 响应。That's it, you've put together a simple program that will call the Translator Text API and return a JSON response. 现在,可以运行该程序了:Now it's time to run your program:

node transliterate-text.js

如果希望将你的代码与我们的进行比较,请查看 GitHub 上提供的完整示例。If you'd like to compare your code against ours, the complete sample is available on GitHub.

示例响应Sample response

[
    {
        "script": "latn",
        "text": "konnichiwa"
    }
]

清理资源Clean up resources

如果已将订阅密钥硬编码到程序中,请确保在完成本快速入门后删除该订阅密钥。If you've hardcoded your subscription key into your program, make sure to remove the subscription key when you're finished with this quickstart.

后续步骤Next steps

另请参阅See also

除了语言检测,还请了解如何使用文本翻译 API 执行以下操作:In addition to language detection, learn how to use the Translator Text API to: