res.json not working correctly with axios / React - reactjs

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.

Related

I make a "GET" call with axios but it doesn't work on the client, if I use Swagger it works

I have an instance of axios with baseURL:"http....".
This instance is imported into data.js to be able to make all calls with axios in another file.
This is data.js:
import axios from 'src/utils/DataService';
function getEwo(id) {
return axios.get('api.../' + id);
}
function getorders(){
return axios.get("api/.../orders");
}
export{getEwo,getorders}
The first call is working, but the second one does not.
In the last file I have the following code:
import * as dataEwo from 'src/dataservice/dataEwo';
const getOrders = useCallback(async () => {
try {
const response = await dataEwo.getorders();
var resp = response.data.data;
if (isMountedRef.current) {
setOrders(resp);
}
} catch (err) {
console.error(err);
}
}, [isMountedRef]);
useEffect(() => {
getOrders();
}, []);
I tried getorders() on Swagger and from BE it returns the data correctly.
If I try to make the same call from the FE client with axios it doesn't work and the BE is queried but the query returns no data and no errors.
Why doesn't axios work in this case?

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 .

Receiving undefined instead of JSON

I am using React axios to receive the JSON (array of objects) from server (server side is written on Go, I checked via Postman, JSON is sent properly).
Here is how I get the data on client side:
export const getPostData = async () => {
const URL = 'http://localhost:8083/test'
try {
const { data: { data }} = await axios.get(URL);
console.log(data)
return data;
} catch (error) {
console.log(error)
}
};
And this is how the getPostData is called in App.js:
const App = () => {
const [ posts, setPosts ] = useState([]);
useEffect(() => {
getPostData()
.then((data) => {
setPosts(data)
console.log(data)
})
},[]);
The problem is I get undefined in browser console. I found many similar questions asked here, but I could not find the solution (the Access-Control-Allow-Origin header is set when I send the JSON).
What should I learn more, where could be the problem? I would be very grateful for any help!
If this could be helpful, here is how I send the JSON in Go:
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Content-Type", "application/json")
c.JSON(http.StatusOK, gin.H{
"message": "Hello",
})
This looks suspect:
const { data: { data }} = await axios.get(URL);
That tries to read a property called data from an object on the data property of the response from axios, like this without the destructuring:
const data = (await axios.get(URL)).data.data;
Your Go code doesn't look like it puts a {"data": ___} wrapper around what it sends, and Axios only adds one layer of {data: ___} wrapper to what it gives you in the response, not two.
If you want the object from the JSON response, remove the inner destructuring:
const { data } = await axios.get(URL);
data will be {message: "Hello"} assuming the Go code sends the JSON {"message": "Hello"}.
Separately, your JavaScript code seems to expect an array of posts, but your Go code is just sending {"message": "Hello"}.

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

React PWA - How do you detect if the requested data to be served from cache or from server

I am building a PWA app, where I download data by a user action call, "Go to offline". So once the button is clicked the data is fetched and saved to the browser indexdb storage. I am using workbox and CRA2. I folled this blog post to customize workbox config with cra app.
Now say there is no PWA, and when page requests data, react call actions for example:
export async function fetchProjectStatuses(
dispatch,
params = {},
raiseError = false
) {
try {
dispatch(requestProjectStatuses());
const data = await fetchProjectStatusesApi();
dispatch(receiveProjectStatuses(data));
return data;
} catch (err) {
if (raiseError) {
throw err;
} else {
dispatch(requestProjectStatusesFailed(err));
}
}
}
and fetchProjectStatusesApi is defined as:
import axios from "axios";
const fetchAllUrl = () => `/project_statuses.json`;
export async function fetchProjectStatusesApi(config, params = {}) {
const url = fetchAllUrl();
const { data } = await axios.get(url, {
headers: { Accept: "application/json" }
});
return data;
}
This works. Now when offline, I am trying to write something like:
import { registerRoute } from "workbox-routing";
registerRoute(
new RegExp("/project_statuses\\.json"),
async ({ url, event, params }) => {
try {
const response = await fetch(event.request);
const responseBody = await response.text();
return new Response(responseBody);
} catch (err) {
// get from DB
}
}
);
So how do I write handler so that it forwards the data to the fetchProjectStatusesApi if network is present , else get data from DB. I know how to pull the date from local IDB. Only thing I am not able to figure out:
How do I detect the app is offline so the data has to come from local db
If app is online how do I forward the response from fetch to axios which is called from the api function.
I am writing it first time so I have no idea yet. Any help will be appreciated.
Thank you.

Resources