【问题标题】:CORS support for Microsoft Azure Translate API?微软 Azure 翻译 API 的 CORS 支持?
【发布时间】:2017-08-30 20:13:12
【问题描述】:

这是一个与https://social.msdn.microsoft.com/Forums/en-US/6e856136-9a39-4b98-a53d-7f8bce08e3a6/cors-support-for-bing-translate-api相关的问题

Microsoft Azure Translate API 现在是否支持 CORS?

【问题讨论】:

    标签: cors microsoft-translator


    【解决方案1】:

    Microsoft Translator Text API 似乎至少现在支持 CORS,因为它至少似乎在响应中发送了 Access-Control-Allow-Origin 标头:

    $ curl -i -H 'Origin: http://example.com' \
      'https://api.microsofttranslator.com/v2/http.svc/Translate?appid=foo&text=hello&from=en&to=de'
    
    HTTP/1.1 400 Bad Request
    Content-Length: 220
    Content-Type: text/html; charset=utf-8
    Access-Control-Allow-Origin: *
    Access-Control-Allow-Headers: X-MS-Trans-Info
    X-MS-Trans-Info: 0642.V2_Rest.Translate.4E779D02
    Date: Wed, 30 Aug 2017 09:07:34 GMT
    
    <html><body><h1>Argument Exception</h1><p>Method: Translate()</p><p>Parameter: appId</p><p>Message: Invalid appId&#xD;
    Parameter name: appId</p><code></code><p>message id=0642.V2_Rest.Translate.4E779D02</p></body></html>
    

    我个人没有有效的 appid 来测试,但如果你有,我想你会发现它会起作用:

    如果可能也适用于https://docs.microsofttranslator.com/text-translate.html POST 端点——只要您的请求不使用Authorization 请求标头或设置Content-Type

    这些标头的问题是,它们会触发浏览器进行预检OPTIONS 请求:

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests

    调用那些触发预检的 API 端点的问题是,它们似乎不会以一种会导致浏览器将预检视为成功的方式响应 OPTIONS 请求。

    https://docs.microsofttranslator.com/text-translate.html#!/default/post_TranslateArray 我注意到文档说端点需要POSTapplication/xmltext/xml Content-Type,所以如果该端点没有以正确的方式响应预检OPTIONS,那个不行。

    这是因为在请求中添加 Content-Type: application/xmlContent-Type: text/xml 标头肯定会触发浏览器在 POST 之前执行预检 OPTIONS

    【讨论】:

    • 正确!我使用的是标题Authorization。文档应该提到你刚才所说的一切
    • 请参阅stackoverflow.com/questions/51626890/… 了解预检响应失败的原因。我在那里建议 CORS 和 V2 曾经可以工作,尽管它看起来可能永远不会工作。正如您将看到的,只有一个小配置阻碍了它。
    猜你喜欢
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 2011-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多