NodeJS 无法从fetch()获取所需响应

gajydyqb  于 2023-06-29  发布在  Node.js
关注(0)|答案(1)|浏览(147)

我使用fake_API在本地网络上显示简单的东西。我使用的是express node.js框架。
app.get('/getEntry/:key', (req, res) => { res.send(getEntry(req.params.key)) return getEntry(req.params.key) })
这应该只显示一些虚拟值,它显示了我在chrome浏览器上所期望的。
screenshot for web
然而,当我获取它时,我无法得到我想要的响应,这是一个字符串“瓦尔is val1”
更新代码:

fetch(`http://${local_IP}:3000/getEntry/${hash}`,{
    Method: 'POST',
    Headers: {
      Accept: 'application.json',
      'Content-Type': 'application/json'
    },
    Cache: 'default'
  })
      .then(response => {
        if (response.ok) {
          return (response.blob())
        } else {
          throw new Error('Error: ' + response.status);
        }
      })
      .then(blob => {
        console.log(blob)
        console.log(2)
      })
      .catch(error => {
        console.error('Error:', error);
        console.log(3)
      });

    }

经过调整,作为slebetman建议现在这上面的代码是更新日志是这样的

{"_data": {"__collector": {}, "blobId": "20D4D114-423D-496A-B5F5-2DF02B644B8A", "name": "Asfa.html", "offset": 0, "size": 11, "type": "text/html"}}

所以现在我有了blob元素,但我仍然没有desire返回,它只是字符串“瓦尔is val1”
响应变量为:

{"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "EC917970-CAB9-4ED1-B7BE-3DD65128C294", "name": "Asfa.html", "offset": 0, "size": 11, "type": "text/html"}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "EC917970-CAB9-4ED1-B7BE-3DD65128C294", "name": "Asfa.html", "offset": 0, "size": 11, "type": "text/html"}}, "bodyUsed": false, "headers": {"map": {"connection": "keep-alive", "content-length": "11", "content-type": "text/html; charset=utf-8", "date": "Thu, 22 Jun 2023 21:22:19 GMT", "etag": "W/\"b-PP2DhlNqgm5t6T/UuubuFEzI4JU\"", "keep-alive": "timeout=5", "x-powered-by": "Express"}}, "ok": true, "status": 200, "statusText": "", "type": "default", "url": "http://${local_IP}:3000/getEntry/Asfa"}

我尝试使用许多不同的方法,如text(),blob(),json()来处理响应,但它们都不起作用。我相信它是blob格式的,但是blob变量是未定义的

xcitsw88

xcitsw881#

将调用返回到response.*

fetch( URL, options )
.then(response => {
  return response.blob() // <-- Return the result of response.blob() so that it's available on the next then() as its first parameter ('blob')
})
.then(blob => {
  console.log(blob) // <-- result of response.blob() is available here
})
.catch(error => {
  console.error('Error:', error);
  console.log(3)
});

当然,你可以用任何你想要的方式来解析响应:

return response.text()
return response.json()
  • 注意:* 对response.*的调用只能发生一次(它是一个只被读取一次的流),这就是为什么你不能同时调用console.log并返回它,因此出现了错误Already read

相关问题