Axios stream ECONNRESET But which side error'd - axios

I am using axios to stream data from an API, something like this
const response = await axios.get(url,
{
responseType: `stream`,
}
);
const stream = response.data;
stream.on(`data`, (data) => {
...
});
stream.on(`error`, (err) => {
...
});
From time-to-time I get an error
{
"code": "ECONNRESET"
}
Does this mean it's the API that is throwing this error as opposed to my application that caused it?
Thank you,

Related

axios how get status error without response

How can i get information about the error when there is no responce in the error? Through postman I see code 404, through catch I see code 0 in the request. How can I get 404 code?
(async () => {
try {
const res = await axios('https://ms.com/s');
}
catch(e) {
console.log(e);
console.log(e.response);
console.log(e.request);
}
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.1.3/axios.min.js"></script>
var response = await axiosbase.get('https://ms.com/s')
.then(response => {
return response;
}).catch(response => {
return response;
});
if(response.status === 200){
// do something here.
}

Axios interceptor not working anymore in last version (1.1.3)

I recently upgraded axios in one of my project (from 0.27 to 1.1.3) and the interceptor I created to refresh the user's access token doesn't work anymore, u can find in the screenshot bellow the error I'm having. I searched online but can't find anything working.
To precise, whenever the user's access token expires, my back end send the 401 error and so the interceptor is called. The returned token is good as well as the setting to the headers.
Thank you in advance for your time.
import axios from "axios";
import router from "#/router";
import store from "#/store/index";
const instance = axios.create({
baseURL: "http://localhost:3000",
});
instance.interceptors.response.use(
(response) => {
return response;
},
async (error) => {
const originalRequest = error.config;
console.log("error:", error);
if (
error.config.url != "users/refreshToken" &&
error.response.status === 401 &&
!originalRequest._retry
) {
originalRequest._retry = true;
await instance
.get("users/refreshToken", { withCredentials: true })
.then((response) => {
const token = response.data.accessToken;
console.log("token:", token);
store.state.token = token;
instance.defaults.headers.common["authorization"] = `Bearer ${token}`;
originalRequest.headers["authorization"] = `Bearer ${token}`;
localStorage.setItem("token", token);
})
.catch(() => {
store.commit("logout");
localStorage.removeItem("token");
router.push({ name: "login", params: { error: "refreshToken" } });
});
return instance(originalRequest);
}
return Promise.reject(error);
}
);
export default instance;
The error :

Facing error while requesting the signup request

who I'm and what I'm trying to do :
I am a beginner following and building a MERN stack project tutorial on youtube
I want to make two requests to the server :
the first request is a register/ signUp request (not working fine).
the second request is a login request (working fine).
errors in my console
POST http://localhost:5000/auth/register 500 (Internal Server Error)
AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}
my console looks like this
source code:
Auth.jsx
const handleSubmit = (e) => {
// setConfirmPass(true);
e.preventDefault();
if (isSignUp) {
data.password === data.confirmpass
? dispatch(signUp(data))
: setConfirmPass(false);
} else {
dispatch(logIn(data));
}
};
AuthRequest.js
import axios from "axios";
const API = axios.create({ baseURL: "http://localhost:5000" });
export const logIn = (formdata) => API.post("/auth/login", formdata);
export const signUp = (formdata) => API.post("/auth/register", formdata);
AuthAction.js
import * as AuthAPI from "../api/AuthRequest.js";
export const logIn = (formData) => async (dispatch) => {
dispatch({ type: "AUTH_START" });
try {
const { data } = await AuthAPI.logIn(formData);
dispatch({ type: "AUTH_SUCCESS", data: data });
} catch (error) {
console.log(error);
dispatch({ type: "AUTH_FAIL" });
}
};
export const signUp = (formData) => async (dispatch) => {
dispatch({ type: "AUTH_START" });
try {
const { data } = await AuthAPI.signUp(formData);
dispatch({ type: "AUTH_SUCCESS", data: data });
} catch (error) {
console.log(error);
dispatch({ type: "AUTH_FAIL" });
}
};
Can somebody tell me why my sighUp request is showing me an error and login is working fine. How to fix that errors.
both request are working fine using thunderclient.
Sorry If I am not able to understand properly here what my problem is. you can open the youtube video link (at time 45:44). this is what I'm trying to do. I have added the cors package also but for the sighup request it is not working.

HTTP .get() method does not respond with anything

I am trying to use Express + MongoDB building React app.
I was able to post some documents to MongoDB and delete them. Currently, I'm trying to figure out how to get them using HTTP .get() method.
I have these routes:
router.post('/totalbalance', (request, response) => {
const totalBalance = new TotalBalanceModelTemplate({
totalBalance:request.body.totalBalance,
});
totalBalance.save()
.then(data => {
response.json(data);
})
.catch(error => {
response.json(error);
});
});
router.get('/totalbalance', (request, response) => {
console.log("Response ", response);
});
This is axios request:
useEffect(() => {
console.log("Using get() method here");
axios.get('http://localhost:4000/app/totalbalance')
}, []);
However, it does not return anything (only 'Using get() method here' gets printed out to the console).
What am I missing here?
Thanks in advance!

detecting error for Nextjs API route with Axios

I am using nextjs api/routes
I have a login and when an issue occurs return a 401 and message text that I would like to show to users.
A minimal example is:
Api : /api/v1/auth/sigin.js
export default async (req, res) => {
const { name, password } = req.body;
const url = process.env.SH_API_BASEURL + 'auth/signin';
console.log(url);
try {
const resp = await axios.patch(url, { name, password });
return res.status(200).send(resp.data);
} catch (err) {
const { response } = err;
const status = response.status;
const message = response.data.errors[0].message;
console.log(`status: ${status}, message ${message}`);
return res.status(status).send(message);
}
};
Pages /pages/auth/signin.js
const handleFormSubmit = async (formData, e) => {
e.preventDefault();
try {
const res = await axios.post('/api/v1/auth/signin', formData);
router.push('/secure/home');
} catch (err) {
console.log('pages auth in error');
console.log(err);
setSubmitError(true);
console.log('sigin handle submit error');
}
};
console.log(err) shows the output
Error: Request failed with status code 401
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:62)
How do I get access to the statusCode and text in pages code?
Could any answers be in the context of nextjs api/routes
Thanks
You can access the response property of the axios error to get the status
const handleFormSubmit = async (formData, e) => {
e.preventDefault();
try {
const res = await axios.post('/api/v1/auth/signin', formData);
router.push('/secure/home');
} catch (err) {
console.log(err.response.status);
}
};