hildjj / node-cbor

Encode and decode CBOR documents, with both easy mode, streaming mode, and SAX-style evented mode.
MIT License
357 stars 73 forks source link

Usage in react #115

Closed g5becks closed 4 years ago

g5becks commented 4 years ago

Hi, I keep getting an error TypeError: Invalid non-string/buffer chunk when trying to decode a cbor response in react.

Is there something extra I need to when attempting to use this module in the browser? Or does it even work in the browser? It works perfectly when using node, so I figure I am either doing something wrong it wasn't designed to be used in that environment.

Thanks.

hildjj commented 4 years ago

I haven't tested in the browser recently. Do you have a simple project I can look at to help diagnose the issue?

I bet you're passing in an ArrayBuffer.

g5becks commented 4 years ago

@hildjj

Hi, I uploaded it here https://github.com/g5becks/cbor_error/tree/master

I used an ArrayBuffer in that example because it is all axios provides besides a blob. I actually never used cbor or this library before, so I am sure this is an error on my part.

If you wouldn't mind providing me a simple example of the correct approach to making this work, it would be highly appreciated.

Thanks.

g5becks commented 4 years ago

@hildjj

I managed to get this working. Thanks for the help.

rivertam commented 3 years ago

@g5becks but how did you manage to get this working?

g5becks commented 3 years ago

@rivertam

Here is an example using axios.

const addInterceptors = (client: AxiosInstance) => {
  client.interceptors.response.use(async (response) => {
      if (response.headers['content-type'] === 'application/cbor') {
        const [data] = await decodeAll(Buffer.from(response.data))
        return { ...response, data: data?.data }
      }
      return { ...response, data: response.data?.data }
    })
  client.interceptors.request.use(async (request) => {
      if (request.headers['content-type'] === 'application/cbor') {
        request.data = await encodeAsync(request.data)
        return request
      }
      return request
    })
}
rivertam commented 3 years ago

Thanks! How do you have Buffer?

rivertam commented 3 years ago

https://github.com/feross/buffer works!

g5becks commented 3 years ago

@rivertam sorry, forgot to mention that part. Glad you found the right package.