【发布时间】:2019-12-07 14:09:30
【问题描述】:
我尝试使用来自 Windows Azure 的一个非常基本的 API 调用来翻译一些文本。他们给了quickstart example code。
我尝试了这段代码,它运行良好。文本Hello world 被翻译成德语和意大利语。
我删除了我的个人订阅密钥。
示例如下:
const request = require('request');
const uuidv4 = require('uuid/v4');
const subscriptionKey = '........';
let options = {
method: 'POST',
baseUrl: 'https://api.cognitive.microsofttranslator.com/',
url: 'translate',
qs: {
'api-version': '3.0',
'to': ['de', 'it']
},
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
body: [{
'text': 'Hello World!'
}],
json: true,
};
request(options, function(err, res, body){
console.log(JSON.stringify(body, null, 4));
});
看起来这段代码是node 的服务器端库。现在我需要将此代码集成到我的 [aurelia][2] 应用程序中。于是想到用aurelia-fetch-client来代替request的方法。我使用 Aurelia CLI。
这是我所做的:
在 package.json 中添加:
"dependencies": {
....
"@types/uuidv4": "^2.0.0",
...
"uuidv4": "^4.0.0",
}
在 aurelia.json 中添加:
"dependencies": [
...
"uuidv4"
]
在我的控制台中运行npm install。
创建了一个测试页:
import { HttpClient, json } from 'aurelia-fetch-client';
import { autoinject } from 'aurelia-framework';
import * as uuidv4 from 'uuidv4';
import secret from '../secret';
@autoinject
export class Translator {
constructor(httpClient: HttpClient) {
this.httpClient = httpClient;
}
private httpClient: HttpClient;
private translate(from, to, html) {
debugger;
var init: RequestInit =
{
method: 'POST',
//mode: 'no-cors',
headers: {
'Ocp-Apim-Subscription-Key': secret.translatorKey,
'Content-type': 'application/json',
//'Content-Type': 'application/x-www-form-urlencoded',
'X-ClientTraceId': uuidv4().toString()
},
credentials: 'same-origin',
body: $.param({
'api-version': '3.0',
'from': 'en',
'to': 'fr',
'text': '<b>Hello World!</b>' })
//body: json({ 'text': '<b>Hello World!</b>' })
};
this.httpClient.fetch(`https://api.cognitive.microsofttranslator.com/`, init)
.then((result) => {
debugger;
})
.catch((error) => {
debugger;
});
}
诀窍是能够将选项传递给示例代码的request,并将其调整为aurelia-fetch-client。我没有成功。
不幸的是,我总是收到以下错误:
访问从源“http://localhost:9000”获取“https://api.cognitive.microsofttranslator.com/”已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:预检请求不允许重定向。
有什么建议吗?
【问题讨论】:
-
在stackoverflow.com/a/42172732/441757 上查看答案。浏览器对
https://api.cognitive.microsofttranslator.com/发出的COR preflight OPTIONS 请求的服务器响应显然是3xx 重定向。检查响应中的 Location 响应标头。您可以使用浏览器开发工具中的网络窗格来查看它。查看响应试图将您重定向到哪个 URL。
标签: typescript cors aurelia azure-cognitive-services aurelia-fetch-client