从node js服务器向客户端发送axios post请求错误消息



如何发送节点JS Axios请求错误消息?我不想在控制台中打印错误,我想把它发送给应用程序。

例如,如果我正在测试邮差,我点击localhost:8080/list/22是错误的id,而不是无休止地显示sending request,我想要返回特定的JSON错误消息。

**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。如何在客户端的Axios请求中使用此错误消息?

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

error.response是一个Axios Response对象,它不能很好地序列化为JSON。

参见Axios -处理错误。

您应该使用上游响应状态和数据进行响应

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

仅供参考,Axiosparams选项用于构造URL查询参数。您的客户端请求应该使用

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

另外,Express有一个更简单的代理库- Express -http-proxy

const proxy = require('express-http-proxy');
app.use("/list", proxy(BASE_URL, {
https: true,
proxyReqPathResolver: (req) => req.originalUrl,
}));

最新更新