Google Translate API v3 要求我们传递“parent”参数。
在他们的示例代码中随处可见,例如:
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'global';
// const text = 'text to translate';
// Imports the Google Cloud Translation library
const {TranslationServiceClient} = require('@google-cloud/translate');
// Instantiates a client
const translationClient = new TranslationServiceClient();
async function translateText() {
// Construct request
const request = {
parent: `projects/${projectId}/locations/${location}`, // <-- HERE
contents: [text],
mimeType: 'text/plain', // mime types: text/plain, text/html
sourceLanguageCode: 'en',
targetLanguageCode: 'sr-Latn',
};
// Run request
const [response] = await translationClient.translateText(request);
for (const translation of response.translations) {
console.log(`Translation: ${translation.translatedText}`);
}
}
translateText();
但我无法在任何地方找到有关此“父”参数是什么、如何填写它以及从何处获取的信息。谁能帮帮我?
最佳答案
parent
参数用于告诉 API 将使用哪个项目和位置来处理请求。有关该参数的更多信息,请参阅 reference .此外,您只需取消注释前几行代码并进行一些更改:
const projectId = 'your-project-id-here'; // see https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects
const location = 'global'; // Do not change this as this is the default location used for Translation API
const text = 'text to translate'; // Replace "text to translate" to whatever text you want to translate to
你的整个代码应该是这样的:
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
const projectId = 'xxxxxxxxxx'; // your project ID that could be seen in the home page of Google Cloud Console
const location = 'global';
const text = 'Hello world'; // the text you want to translate
// Imports the Google Cloud Translation library
const {TranslationServiceClient} = require('@google-cloud/translate');
// Instantiates a client
const translationClient = new TranslationServiceClient();
async function translateText() {
// Construct request
const request = {
parent: `projects/${projectId}/locations/${location}`, // get the values of projectId and location variable declared at the start of the code
contents: [text],
mimeType: 'text/plain', // mime types: text/plain, text/html
sourceLanguageCode: 'en',
targetLanguageCode: 'sr-Latn',
};
// Run request
const [response] = await translationClient.translateText(request);
for (const translation of response.translations) {
console.log(`Translation: ${translation.translatedText}`);
}
}
translateText();
关于node.js - Google Cloud Translate Advanced (V3) 中的 "parent"参数是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67030462/