API connected to Redis returns value when called by cURL, but not when called by Axios

Viewed 448

I have a ExpressJS API set up to service requests from the front end, connecting it to my Redis Database. One endpoint takes in a parameter specified in the request URL(GET request), and returns a number. When I use Axios or Node-Fetch to hit this endpoint, it returns null, which is what Node-Redis returns if the key does not exist. When I hit this endpoint with cURL and Chrome, it returns the correct number. Other endpoints function correctly. Why is this?

Server Code:

router.get("/api/:id/bal", async (req, res) => {
    let id = req.params.id;
    await client.get(id, (err, response) => {
      if (err) throw err;
      res.send(response);
    });
  }); 

Axios call:

axios.get(`http://localhost:4000/api/${id}/bal`)
  .then((response) => {
     console.log(response.data);
})

cURL call:

curl http://localhost:4000/api/id/bal -i

(in both id is replaced by a real account id)

1 Answers

Not sure if this will help but, mixing callbacks and async/await is not recommanded. Depending on what redis library you use it may be different, but I will assume you are using node-redis, which by default is not promisified, so you have to stick with callbacks:

router.get("/api/:id/bal", (req, res, next) => {
    let id = req.params.id;
    client.get(id, (err, response) => {
      if (err) return next(err); // do not throw inside callbacks !
      // if you do nobody catch the error
      // you have to pass it to `next` to let express handle it.
      console.log('redis response:', response); // added a log so we can check the value
      res.send(response); // maybe more need to be done here, proper formating ?
    });
  });

Or you can promisify redis yourself (you need node 8+ and express 5+ for that):

const { promisify } = require("util");
const getAsync = promisify(client.get).bind(client);
router.get("/api/:id/bal", async (req, res) => {
    let id = req.params.id;
    const response = await getAsync(id);
    console.log('redis response:', response)
    res.send(response);
  });

here since we use async/await the error will be catched and handled by express without needing to use callbacks and next !

Now just check the logs, if it fails maybe try to send it as JSON with res.json(response) ?

Related