ipfs / helia

An implementation of IPFS in JavaScript
https://helia.io
Other
811 stars 81 forks source link

TypeError: Cannot read properties of undefined (reading 'code') when retrieving JSON from CID #559

Closed medkhalilbk closed 6 days ago

medkhalilbk commented 1 week ago

Hello Community,

I'm trying to use Helia in a Node.js server environment. When I store files, I receive a CID without any issues. However, when I try to retrieve the JSON from the CID, I encounter the following error:

TypeError: Cannot read properties of undefined (reading 'code')

Here is my code

import express from 'express';
import { createHelia } from 'helia';
import { json } from '@helia/json';
import bodyParser from 'body-parser';

const app = express();

app.use(bodyParser.json());

const helia = await createHelia();
const j = json(helia);

app.get('/', (req, res) => {
  console.log(req);
  res.send('Hello World');
});

app.post('/store', async (req, res) => {
  try { 
    const jsonData = req.body; 
    const cid = await j.add(jsonData); 
    res.json({ cid: cid.toString() });
  } catch (error) {
    console.error(error);
    res.status(500).send('Error storing JSON in IPFS');
  }
});
app.get('/get/:cid', async (req, res) => {
  try { 
    const {cid} = req.params 
    const jsonData = await j.get(cid);
    res.json(jsonData);
  } catch (error) {
    console.error(error);
    res.status(500).send('Error retrieving JSON from IPFS');
  }
})

// Start server
app.listen(5000, () => {
  console.log('Server is running on port 5000');
});

Steps to Reproduce:

  1. Start the server with node server.js.
  2. Use a tool like Postman to send a POST request to http://localhost:5000/store with a JSON body.
  3. Note the returned CID.
  4. Use the returned CID to send a GET request to http://localhost:5000/get/{cid}.

Expected Behavior:

Actual Behavior:

The server returns a TypeError: Cannot read properties of undefined (reading 'code').

Additional Context:

Node.js version: 18.17.1 Helia version: 4.2.3 Can anyone help me resolve this issue?

Thank you! 🙏

tabcat commented 1 week ago

Without investigating, my guess is that you need to parse the cid string into a CID with CID.parse before passing to j.get.

medkhalilbk commented 6 days ago

@tabcat Thanks, this works well.