Repository navigation
can I use axios to modify response in the http layer or in a browser environment ? #6213
Replies: 1 comment
|
Yes. Axios interceptors can run in both Node.js and the browser, but they only affect requests made by that Axios instance in the environment where that code runs. If your interceptor runs in Node, the browser will not automatically see that modified response. You need to send the modified data back to the browser yourself. Example in Node/Express: app.get("/api/users", async (req, res, next) => {
try {
const response = await axios.get("https://example.com/users");
const modifiedData = response.data.map(user => ({
...user,
displayName: `${user.firstName} ${user.lastName}`
}));
res.json(modifiedData);
} catch (err) {
next(err);
}
});If you want the modification to happen in the browser, define the interceptor in browser-side code and use that Axios instance for the request: const api = axios.create();
api.interceptors.response.use(response => {
response.data = {
...response.data,
modified: true
};
return response;
});
const { data } = await api.get("/api/users");
// Render using `data`.Important distinction: Axios interceptors do not modify the browser's general HTTP layer. They only intercept requests made through Axios. If the page uses |
Uh oh!
There was an error while loading. Please reload this page.
I'm using axios interceptors to modify an api response and it is successfully modified but it intercepts at the node layer and I'm not sure how to feed that to the browser or intercept in a browser env so the page renders accordingly.
All reactions