2

I'm using Superagent in my react app, and i'm making some call's to the IPFS api. Specifically, I am uploading files to my IPFS server. Now, everything works, When I upload one or multiple files the call goes through and the files show up in IPFS no problem.

A problem occurs when I upload multiple files though, the response seems to come back as plain text, instead of JSON, and superagent throws the error

client.js:399 Uncaught (in promise) Error: Parser is unable to parse the response
    at Request.<anonymous> (client.js:399)
    at Request.Emitter.emit (index.js:133)
    at XMLHttpRequest.xhr.onreadystatechange (client.js:708)

So to be clear, when uploading a single file, I get a nice JSON response, but when I upload multiple files, the response is in plain text.

Can I force Superagent to give me the response back and parse it myself? Or can I set something when making the call so that it forces a json parse? Below is my superagent request function

  add : acceptedFiles => {
    const url = ipfs.getUrl("add")
    const req = request.post(url)

    acceptedFiles.forEach(file => req.attach(file.name, file))

    req.then(res => {
      return console.log(res);
    })
  }
Shan Robertson
  • 2,742
  • 3
  • 25
  • 43

2 Answers2

1

I'm searching for this for a more elegant solution, but before I would have found it , I'd like to provide my own solution.


I think this problem caused by wrong responsive Content-Type set, but I've not confirmed this opinion yet.

However, you can try this:

req.catch(function (err) {
    console.log(err.rawResponse)
})

At least, this solves my problem.

Rika
  • 21
  • 2
  • 3
1

According to their docs you can specify custom parser that will take precedence over built-in parser:

You can set a custom parser (that takes precedence over built-in parsers) with the .buffer(true).parse(fn) method. If response buffering is not enabled (.buffer(false)) then the response event will be emitted without waiting for the body parser to finish, so response.body won't be available.

I tried and it worked well for me.

superagent.get('....')
    .buffer(true)
    .parse(({ text }) => JSON.parse(text))
    .then(...)
skyboyer
  • 22,209
  • 7
  • 57
  • 64