CORS support for Microsoft Azure Translate API?

旧巷老猫 提交于 2019-12-13 19:59:57

问题


This is a question related to https://social.msdn.microsoft.com/Forums/en-US/6e856136-9a39-4b98-a53d-7f8bce08e3a6/cors-support-for-bing-translate-api

Does the Microsoft Azure Translate API support CORS now?


回答1:


The Microsoft Translator Text API appears to at least minimally now support CORS, in that it does at least seem to send the Access-Control-Allow-Origin header in responses:

$ 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>

I don’t personally have a valid appid to test with—but if you do, I think you’ll find it’ll work:

  • if you use GET endpoints from the https://docs.microsofttranslator.com/text-translate.html docs
  • if you authenticate using the appid parameter instead of the Authorization request header

If may also work for the https://docs.microsofttranslator.com/text-translate.html POST endpoints—as long as your requests don’t use the Authorization request header or set a Content-Type.

The problem with those headers is, they’ll trigger browsers to do a preflight OPTIONS request:

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

And the problem with making calls to those API endpoints that trigger a preflight is, they don’t seem to respond to OPTIONS requests in a way that’ll cause browsers to see the preflight as a success.

At https://docs.microsofttranslator.com/text-translate.html#!/default/post_TranslateArray I notice the docs say that endpoint expects a POST with an application/xml or text/xml Content-Type, so if that endpoint doesn’t respond to preflight OPTIONS in the right way, that one won’t work.

That’s because adding an Content-Type: application/xml or Content-Type: text/xml header to a request will definitely trigger browsers to do a preflight OPTIONS before the POST.



来源:https://stackoverflow.com/questions/45954767/cors-support-for-microsoft-azure-translate-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!