对Microsoft Azure的React Native fetch请求失败

时间:2018-02-22 20:50:14

标签: reactjs azure http react-native fetch

我正在尝试使用找到here的Microsoft Azure OCR API来获取React Native应用。

我可以使用Postman让API在本地图像上正常工作,但出于某种原因,当我在我的应用中尝试使用fetch时,我会收到“不支持的媒体类型”。

我最初用这段代码调用了api:

_analyzeImage = () => {
    const { image } = this.state;
    const url = 'https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/ocr';
    const data = new FormData();
    data.append(image);
    fetch(url, {
        method: 'post',
        body: data,
        headers: {
            'Ocp-Apim-Subscription-Key': '***********************',
        }
    }).then(res => {
        console.log(res)
    });
}

image的样子:

enter image description here

当使用XCode模拟器运行时,产生:

enter image description here

回复:

{
  "code":"UnsupportedMediaType",
  "requestId":"6ff43374-e5f9-4992-9657-82ec1e95b238",
  "message": "Supported media types: application/octet-stream, multipart/form-data or application/json"
}

很奇怪,content-type似乎是test/plain。因此,即使我认为FormData对象应该处理内容类型,我尝试添加'content-type': 'multipart/form-data',但得到相同的响应(尽管网络检查器中的content-type标题确实更改为{ {1}}。

我使用multipart/form-data来设置项目,并希望在iOS和Android上工作。如果有人有任何想法 - 或任何其他方式做OCR,如果有更好的原生解决方案 - 我会很感激!

1 个答案:

答案 0 :(得分:1)

doc page you link to所述,如果您发送

application / json ,您的有效负载必须如下所示:

{"url": "http://example.com/images/test.jpg"}

如果 application / octet-stream

[Binary image data]

如果 multipart / form-data

[Binary image data]

现在你没有发送符合预期的任何东西。

示例POST

图片,

hello

按网址传递图片:

$ curl -v -X POST -H 'Ocp-Apim-Subscription-Key: 2exxxxxxxxxxxxxxxxxxxxxx' \
                  -H 'Content-type: application/json' \
                  --data-ascii '{ "url": "https://i.stack.imgur.com/RM7B3.png" }' \
                  https://westus.api.cognitive.microsoft.com/vision/v1.0/ocr

> POST /vision/v1.0/ocr HTTP/1.1
> Content-type: application/json
> Content-Length: 44
...

< HTTP/1.1 200 OK
< Content-Length: 196
< Content-Type: application/json; charset=utf-8

{
  "language": "en",
  ...
  "regions": [
    {
    ...
          "words": [
            {
              "boundingBox": "61,49,303,108",
              "text": "hello."
            }
    ...

或通过原始字节传递图像:

$ curl -v -X POST -H 'Ocp-Apim-Subscription-Key: 2exxxxxxxxxxxxxxxxxxxxxx' \
                  -H 'Content-type: application/octet-stream' \
                  --data-binary @hello.png \
                  https://westus.api.cognitive.microsoft.com/vision/v1.0/ocr

> POST /vision/v1.0/ocr HTTP/1.1
> Content-type: application/octet-stream
> Content-Length: 11623
...

< HTTP/1.1 200 OK
< Content-Length: 196
< Content-Type: application/json; charset=utf-8

{
  "language": "en",
  ...
  "regions": [
    {
    ...
          "words": [
            {
              "boundingBox": "61,49,303,108",
              "text": "hello."
            }
    ...