Getting Error Response using axios on Client Side in React - reactjs

I am learning react. I have written backend code as follows.
router.post('/signup', async (req,res)=>
{
try
{
const user = new User(req.body);
const token = await user.generateAuthToken();
res.cookie('authToken', token);
res.status(201).send();
}
catch(err)
{
res.status(400).send({err: "User Already Exists"});
}
})
on fontend, I am using axios to send request. my code is as follows.
e.preventDefault();
try
{
const res = await axios.post("/signup",{email, password});
}
catch(err)
{
console.log(err)
}
My Question is how can I get User Already Exists this statement from backend in case of error.

In case of any response other than 2xx from backend, the catch block runs on frontend and we can get data using err.response object. To get data, use the following code
try
{
const res = await axios.post("/signup",{email, password})
console.log(res.data)
}
catch(err)
{
if(err.response)
{
console.log(err.response.data)
}
}

Something else broke your function and you have to debug what is wrong here:
catch(err){
console.log(err)
res.status(400).send({err: "User Already Exists"});
}

Related

Why is the response data going to the catch block after await in Axios?

err.response.data giving back the data I am looking for !!
Status code 302
The data is captured in the catch block instead of try block
This is the reudx slice code
export const getAllProject = async (dispatch) => {
try {
console.log("before");
const res = await apiLink.get(`/getAllProjects`);
console.log(res.data);
console.log("after");
dispatch(getAllProjectSuccess(res.data));
} catch (error) {
console.log(error.response.data);
// toast.error(error.response?.data.message);
}
};
The API is calling and the data is also coming.
I inspected the network tab
And also working in postman
But after the await, the code is not running.
React router version 5 is used in this project.
this is the proof of API calling
and
using axios interceptor like this
apiLink.interceptors.request.use(
async (config) => {
const TOKEN = JSON.parse(localStorage.getItem("accessToken"));
config.headers["authorization"] = "Bearer " + TOKEN;
return config;
},
(error) => {
return Promise.reject(error);
}
);
apiLink.interceptors.response.use(
function (response) {
return response;
},
function (err) {
if (err.response?.status === 500) {
userLogout();
}
return Promise.reject(err);
}
);
export default apiLink;
Edited:
err.response.data giving back the data I am looking for !!
I just log that and the status code of receiving the data is 302 .

res.json not working correctly with axios / React

What I want to do :
I send the GET request through axios
I open a local Json file with fs.readfile
I process the data and return it
I want to display the data when it return with res.json
what actually happened
I send the GET request through axios
I open a local Json file with fs.readfile
They return the data before fs.readfile finished so it's undefined or blank
This one I put on the frontend and the controller
//frontend
const fetchRewards = async()=>{
let link ="/api/reward";
const {data} = await axios.get(link);
console.log(data); **// this one logging undefined**
}
// on controller
async getRewardsById(req,res,next) {
try {
const result = await rewardService.getReward();
res.json(result);
} catch (error) {
next(error);
}
},
This is my service
const getReward = async () => {
fs.readFile("test.json", (err, inputData) => {
return {"name":"John", "age":30, "car":null};
}
console.log("done");
}
Seems to me like you are not returning anything from your service?
Try returning the fs.readFile.

How to connect API in reactjs

I and my team are working in Reactjs and I'm completely new to this my part is Connect to API and I follow many resources on the internet, and I don't know that am I on the right track here the code that I did, can someone tell me what I am doing wrong? This part is on the client I want to connect API to the server.I've recieved error:Unexpected reserved word 'await'
useEffect(()=>{
try {
const requestUrl = 'http://localhost:3000/';
const response = await fetch(requestUrl);
const requestJSON = await response.json();
console.log({responseJSON});
const {data} = responseJSON;
setPostEvent(data)
} catch (error) {
console.log('Failed to fetch post list: ',error.message);
}
fetchPostEvent()
},[events])
useEffect(()=>{
localStorage.setItem('events',JSON.stringify(events));
},[events]) ```
You are to use await key word, in an async function. This is how you would make your function async:
useEffect(async()=>{
try {
const requestUrl = 'http://localhost:3000/';
const response = await fetch(requestUrl);
const requestJSON = await response.json();
console.log({responseJSON});
const {data} = responseJSON;
setPostEvent(data)
} catch (error) {
console.log('Failed to fetch post list: ',error.message);
}
fetchPostEvent()
},[events])

React Native Axios Call Inside Function

I tried to put POST by AXIOS function inside another function to reuse it multiple times. but unfortunately It doesn't work as I expected (which was working using FETCH),
AXIOS CALL JS:
export async function post(apiRoute, body) {
try {
body = JSON.stringify(body);
axios.post(apiRoute, body, httpOptions)
.then((res)=>{
console.log(res.data); // I have data here
return res.data;
});
}
catch (err) {
console.log(err);
return err;
}
}
And the caller is:
async DoLogin(userName, password) {
var data = await post(url,{ // post is axios method defined above in another file
UserName: userName,
Password: password
});
return data; // I have nothing here
}
And the problem is I got undefined in DoLogin but got data inside POST method, It seems the problem is related to timing, axions returns a promise which is not possible to read in DoLogin, how I can do this? I did this via FETCH and it works perfectly.
try using async-await in this way.
export async function post(apiRoute, body) {
try {
const response = await axios.post(apiRoute, body, httpOptions)
return response.data;
}
catch (err) {
return err;
}
}

ReactNative: AsyncStorage not working properly

Hello I am trying to impliment a login and the most of the logic is inside action creator but for some react my code doesn't execute after
await AsyncStorage.setItem('adminFlag', adminFlag);
await AsyncStorage.setItem('token', token);`
the console.log(data) is working before this statement...I have no idea why this is happening
export const verifyPassword = (
adminFlag,
password,
navigate
) => async dispatch => {
loadingStatus(dispatch, true);
try {
const { data } = await axios.post(
"myurl with response success--lajja--token",
{
admin: adminFlag,
job: "verifyPassword",
password
}
);
if (data.includes("--lajja--")) {
//spliting the token and the response
const destructuredData = data.trim().split("--lajja--");
const response = destructuredData[0];
const token = destructuredData[1];
console.log(data);
await AsyncStorage.setItem("adminFlag", adminFlag);
await AsyncStorage.setItem("token", token);
navigate();
loadingStatus(dispatch, false);
}
loadingStatus(dispatch, false);
} catch (e) {
console.log(e);
loadingStatus(dispatch, false);
}
};
the lines after console.log(data) are not working...
The problem happened to me as well as to some people on this issue. This seems to happen on Android devices (only during debug) that are running some background activities as specified here and here. The pull request provided by #github/jsdario to fix that issue seems to have not passed the CI though. I guess for now we have to debug... Without the debugger attached.

Resources