代码之家  ›  专栏  ›  技术社区  ›  obiwankenoobi

http POST请求响应“状态”:200,但对象为空

  •  1
  • obiwankenoobi  · 技术社区  · 6 年前

    我正在尝试将一个API用于HTTP POST请求,它似乎可以工作,但当我得到响应时,它是空的。

    API应接收 base64 身体内部的编码图像。

    论点 imageToRead 来自一个承诺 Camera 组件来自 react-native-camera .我不确定可能是那里的问题?

    内容如下: imageToRead = "/var/mobile/Containers/Data/Application/01B81FC9-B171-11GB-9B48-9D06F89B175A/Documents/3A997ACD-D63C-41BD-9041-FDB834A0672A.jpg"

    此API还可以接收 formData 文件,这就是我测试它的方式,它在节点环境中运行得非常好。但由于我的应用程序是本机iOS应用程序,我必须使用其他工具(如React native),不能使用相同的工具。

    在节点中测试API的代码:

    var formData = {image: fs.createReadStream('/Users/Desktop/APITest/img/testOCR8.jpg')};
    request.post({
    url:'${url}', 
    formData: formData},
    (err, httpResponse, body) => {
        if (err) {
            return console.error('upload failed:', err);
        }
        console.log(body);
    
    });
    

    你可以看到我使用 fs.createReadStream fs 模块创建文件流,然后在请求正文中使用它。 我无法使用React-Native复制相同的内容(如果您有一个解决方案,我可以使用React-Native进行复制,那会更好!!)

    所以我尝试了不同的方式,并尝试对从 camera.capture() 随附的方法 反应本机摄像头 基本64 把它放在身体里,但我得到的反应是空的,没有任何错误,只是一个空的物体。

    带有React Native的代码:

    recognise = (imageToRead) => {
        RNFetchBlob.fs.readFile(imageToRead , 'base64')
          .then((data) => {
            fetch('${url}',{
            method: "POST",
            headers: {
               'Accept': 'application/json',
               'Content-Type': 'application/json'
            },
            body: data // the body contain the encoded image
            })
          .then((res) => {  // promise returned with the response from the API
            console.log(`i am the base64Image: ${data}`)
            console.log('i am response', res)
          })  
          .catch((errInFetch) => { // catch any error in the API
            console.log('i am error:', errInFetch)
          })
        })
        .catch((err) => {
          console.log(err);
        })
      }
    

    答复:

    { type: 'default',
      status: 200,
      ok: true,
      statusText: undefined,
      headers: 
       { map: 
          { server: [ 'nginx/1.10.3' ],
            'content-type': [ 'application/json; charset="utf-8"' ],
            'access-control-allow-origin': [ '*' ],
            date: [ 'Thu, 10 May 2018 10:17:48 GMT' ],
            'access-control-allow-headers': [ 'x-requested-with' ],
            'content-encoding': [ 'gzip' ],
            'content-length': [ '237' ],
            connection: [ 'keep-alive' ] } },
      url: 'https://api.openalpr.com/v2/recognize_bytes?secret_key=key&country=eu',
      _bodyInit: 
       { _data: 
          { size: 371,
            blobId: '5080ACA4-5D13-469C-B755-96B06A161FC6',
            type: 'application/json',
            offset: 0,
            name: 'recognize_bytes' } },
      _bodyBlob: 
       { _data: 
          { size: 371,
            blobId: '5080ACA4-5D13-469C-B755-96B06A161FC6',
            type: 'application/json',
            offset: 0,
            name: 'recognize_bytes' } } }
    

    我希望有人能帮上忙。我和它斗争了这么长时间。

    3 回复  |  直到 6 年前
        1
  •  2
  •   Revansiddh    6 年前

    fetch 返回a promise 包含响应(响应对象)。然后再次需要使用 response.json() 返回承诺解析 JSON

    fetch(url, {
        body: JSON.stringify(data),
        cache: 'no-cache', 
        headers: {
          'user-agent': 'Mozilla/4.0 MDN Example',
          'content-type': 'application/json'
        },
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
      })
      .then(response => response.json())
    

    有关详细信息: read

        2
  •  1
  •   FaiChou    6 年前
          .then((res) => { 
            console.log(`i am the base64Image: ${data}`)
            console.log('i am response', res)
            return res.json();
          })  
          .then(res => {
            console.log(res);
          })
          .catch((errInFetch) => { // catch any error in the API
            console.log('i am error:', errInFetch)
          })
    

    Fetch响应体返回一个将由json()解析的承诺。

    所以你可以从 res.json()

        3
  •  -1
  •   Hani Majali 2015    6 年前

    200状态表示成功获取http请求。您的API应该返回状态201,以便post显示消息,而不是200,例如:

    res.status(201).send(data);
    

    full example

    also, you can look at the status 201 description