MS 翻译器请求未获授权

MS translator request not authorized

我有这个简单的代码来获取翻译:

    var apiurl = 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0';
    var my_token = 'xxxxxx'; // my sekret key
        jQuery.ajax({
            url: apiurl,
            dataType: "json",
            jsonp: "oncomplete",
            crossDomain: true,
            context: this,
            data: {
                text: 'Test simple text',
                from: 'en',
                to: 'de'
            },
            beforeSend: function (xhr) {
                xhr.setRequestHeader('Ocp-Apim-Subscription-Key', my_token);
                xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8');
                xhr.setRequestHeader('X-ClientTraceId', uuid());
                xhr.setRequestHeader('Ocp-Apim-Subscription-Region', 'westeurope');
            },
            contentType: "application/json; charset=UTF-8",
            type: 'POST',
            success: function (msg) {
                console.log(msg);
            },
            complete: function (msg) {
            },
            error: function (e) {
                console.log(e);
            }
        });

但我总是收到错误 401000 请求未被授权,因为凭据丢失或无效。

我使用了图片中的秘密 ID。

您的屏幕截图显示了 Azure Active Directory 中的应用程序注册配置页面 - 这是完全不同的东西。你想要的是 creating a Translator resource 然后从“Keys and Endpoints”菜单中取出其中一个键:

通过以下调整,代码应该可以工作:

  • my_token“Azure 门户 > 转换器资源 > 密钥和终结点 > 密钥 1 或密钥 2”下的订阅密钥之一中使用
  • 检查 Ocp-Apim-Subscription-Region 的区域(身份验证也需要),使用“Azure 门户 > 翻译器资源 > 密钥和终结点 > 区域”下的术语
  • apiurl 中插入:&from=en&to=de
  • 更改 数据 在:JSON.stringify([{ 'text': 'Test simple text' }])

var apiurl = 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=en&to=de';
var my_token = 'xxxxxx'; // subscription key
jQuery.ajax({
    url: apiurl,
    dataType: "json",
    jsonp: "oncomplete",
    crossDomain: true,
    context: this,
    data: JSON.stringify([{ 'text': 'Test simple text' }]),
    beforeSend: function (xhr) {
        xhr.setRequestHeader('Ocp-Apim-Subscription-Key', my_token);
        xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8');
        xhr.setRequestHeader('X-ClientTraceId', uuid());
        xhr.setRequestHeader('Ocp-Apim-Subscription-Region', 'westeurope');
    },
    contentType: "application/json; charset=UTF-8",
    type: 'POST',
    success: function (msg) {
        console.log(msg);
    },
    complete: function (msg) {
    },
    error: function (e) {
        console.log(e);
    }
});

function uuid() {
  return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
    (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  );
}