Home > Enterprise >  Send axios post request error message from node js server to client side
Send axios post request error message from node js server to client side

Time:12-08

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);
      });
  };

CodePudding user response:

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,
}));
  • Related