2

How can I send a node JS Axios request error message? I don't want to print the error in the console, I want to send it to the application.

For instance, if I am testing on postman and i hit localhost:8080/list/2 and 2 is the wrong id, instead of endlessly showing sending request, I want the specific JSON error message returned.

**server.js** proxy server running on localhost:8000 makes request to another endpoint

app.get("/list/:id", function (req, res) {
  const { id } = req.params;
  axios
    .get(`${BASE_URL}/list/` + id)
    .then((response) => {
     res.send(response.data)
    })
    .catch((error) => {
       if(error.response) {
            res.send(error.response)
        }
    });
});

2. How can this error message be used in an Axios request on the client side?

const getList = () => {

    axios
      .get("http://localhost:8000/list", {
          params: {
            id: '4'
          }
        })
      .then((resp) => {
        const data = resp.data; 
        console.log(resp.data)

      })
      .catch((err) => {
        console.error(err);
      });
  };
Tini
  • 169
  • 8
  • When you pass correct id do you see response in postman? if yes then my guess is your error object doesn't have response property and that's why it doesn't go inside if block. – Anil Dec 08 '22 at 01:28
  • 1
    You've confused route and query parameters. Use `axios.get("http://localhost:8000/list/4")` instead. The `params` option is for creating query parameters – Phil Dec 08 '22 at 01:51

1 Answers1

2

The error.response is an Axios Response object which doesn't serialise to JSON very well.

See Axios - Handling Errors.

You should respond with the upstream response status and data

app.get("/list/:id", async (req, res, next) => {
  const { id } = req.params;
  try {
    const { data } = await axios.get(`/list/${id}`, {
      baseURL: BASE_URL,
    });
    res.send(data);
  } catch (err) {
    if (err.response) {
      res
        .status(err.response.status) // proxy the status
        .send(err.response.data); // proxy the data
    }
    next(err); // some other error
  }
});

FYI, the Axios params option is for constructing URL query parameters. Your client-side request should use

axios.get("http://localhost:8000/list/4")

Another FYI, Express has a much simpler proxy library - express-http-proxy

const proxy = require('express-http-proxy');

app.use("/list", proxy(BASE_URL, {
  https: true,
  proxyReqPathResolver: (req) => req.originalUrl,
}));
Phil
  • 157,677
  • 23
  • 242
  • 245