not able to fetch api response - reactjs

I have written an API where I am generating data in JSON format.
Now I am calling same API on react frontend. If response is generated we will display a success page else we will divert to same page. So I have written these code when I submit user id and password on submit event validateLogin API has been called, but I am not able to execute body of API response.
onSubmit = async => {
const { user_mail, user_pass1 } = this.state
const payload = { user_mail, user_pass1}
api.validateLogin(payload).then((res) =>{
alert('Success');
})
.catch((err) =>{
alert('Failed');
})
}
Here nothing is executing. Can you please help me to execute response body?

Related

Axios API call returns a 404 on page render, but still returns api objects in terminal

I am using axios to make an api call to an api found on Apihub for a next JS app.
here is the code for the function to make the call to provide a list of property JSON objects.
export const baseUrl = "https://zillow56.p.rapidapi.com"
export const fetchApiListsingsCustom = async (url) => {
const { data } = await axios.get((url), {
method: 'GET',
headers: {
'X-RapidAPI-Key': '328713ab01msh862a3ad609011efp17e6b4jsn0e7112d5ee9a',
'X-RapidAPI-Host': 'zillow56.p.rapidapi.com'
}
});
data.then((res) => {
console.log(res);
})
.catch((error) => {
console.error(error);
});
return data.json();
}
When rendering the page I'm attempting to inject the response's data to dynamically create a list of apartment listings.
I'm trying to use getServerSideProps so that the data is already available by the time a user requests the page. After fetching the data, I want to also print them in the terminal to validate it's success.
export default function Home({ propertiesCustomdata })
export async function getServerSideProps() {
const propertiesCustom = await fetchApiListsingsCustom(`${baseUrl}`)
const propertiesCustomdata = propertiesCustom.json()
return {
props: {
propertiesCustomdata
}
}
}
The problem is, I seem to be getting a 404 error from the axios call, before the page gets a chance to load. When I access this I get a 404 error but I also manage to receive some contents of the call the API was to make.
My apologies if this is unclear, but this is all I know to report on this so far.
Studying async and await, fetch, and axios. Very confusing.

image is not loading and being blocked by CORB

I am getting a data with an image link and I want to show those images by using the link in my img tag. I have disabled CORS on my chrome and I am receiving the data successfully but when I try to render the image it gives me an error "Cross-Origin Read Blocking (CORB) blocked cross-origin response https://commons.wikimedia.org/wiki/File:A_Conversation_With_Oscar_Wilde_-_London_-_240404.jpg with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details"
Can you please help on how can I bypass this. I am using axios for to make the fetch request and React to render the image.
async function getData(location) {
try {
// Make API call to get coordinates of location
const geonameResponse = await axios.get(`https://api.opentripmap.com/0.1/en/places/geoname?name=${location}&apikey=${API_KEY}`)
//console.log(geonameResponse)
// Make API call to get features within 1000 meter radius of location
const radiusResponse = await axios.get(
`https://api.opentripmap.com/0.1/en/places/radius?radius=1000&lon=${geonameResponse.data.lon}&lat=${geonameResponse.data.lat}&limit=10&apikey=${API_KEY}`)
//console.log(radiusResponse)
// Make API call for each feature to get more detailed information
// Make API call for each feature to get more detailed information
const xidResponses = await Promise.all(
radiusResponse.data.features.map(async (item) => {
return new Promise((resolve) => {
setTimeout(async () => {
resolve(await axios.get(
`https://api.opentripmap.com/0.1/en/places/xid/${item.properties.xid}?apikey=${API_KEY}`
));
}, 2000);
});
})
);
// Set data to array of xidResponses
setData(xidResponses);
} catch (error) {
console.error(error);
}
}

OpenApi generated typescript not properly calling api from React Webapp

I have a react webapp and a spring boot java backend api. The backend Api works perfectly fine with postman.
In the react webapp, I am using openapi generated typescript to make the calls to the backend api. I have two parameters for the api, a number and an object. The object is just json style object.
When I use the typescript to call the api, for some reason, it passes in null for the object parameter and the api returns a 500 error. I have no clue why this is happening. Any suggestions? Here is the code where I call the api:
function gatherUserData(){
const UserDataRetval: UserData = {};
UserDataRetval.version = kVersion;
UserDataRetval.Methods = [];
if (checkedLikesYouCount){
UserDataRetval.Methods.push(UserDataMethodsEnum.RECOM_LIKES_YOU_COUNT)
}
if (checkedRecosRecommendations){
UserDataRetval.Methods.push(UserDataMethodsEnum.RECOS_RECOMMENDATIONS)
}
if (checkedUsersRecommendations){
UserDataRetval.Methods.push(UserDataMethodsEnum.USERS_RECOMMENDATIONS)
}
if (checkedProfileUser){
UserDataRetval.Methods.push(UserDataMethodsEnum.PROFILE_USERID)
}
if (checkedProfile){
UserDataRetval.Methods.push(UserDataMethodsEnum.PROFILE)
}
if (checkedRecosLikesYou){
UserDataRetval.Methods.push(UserDataMethodsEnum.RECOS_LIKES_YOU)
}
if (checkedRecommendationsLikesYou){
UserDataRetval.Methods.push(UserDataMethodsEnum.RECOM_LIKES_YOU)
}
return UserDataRetval;
}
//USER CLICKS SUBMIT BUTTON, CHECKS USERID ISNT EMPTY, BRINGS UP JSON DATA
function handleSubmit() {
console.log("Call API for methods:")
console.log(userid)
SetDisplayJson(userid !== "")
auth.onAuthStateChanged(user => {
if (user) {
user.getIdTokenResult(false)
.then(tokenResult => {
console.log("token: ", tokenResult.token)
new ServiceApi(headerConfig(tokenResult.token)).simulateUser(parseInt(userid), gatherUserData()).then((response) => {
console.log(response);
}, (error) => {
console.log(error);
})
}).catch(e => console.log(e))
}
})
}

ReactJS axios POST call to PHP - Request Aborted error

I am trying to make a POST call to a PHP file with axios.
loginHandler = () => {
var params = new URLSearchParams();
params.append('User', this.state.inputUsername);
params.append('Pwd', this.state.inputPassword);
var callAction = process.env.REACT_APP_API_ENDPOINT + 'LoginHandler.php';
axios.post(callAction, params)
.then(res => {
const message = res.data;
console.log(message);
})
.catch(function (error) {
// handle error
console.log(error);
})
}
But everything I try seems to give me a "Request aborted" error.
However, doing axios requests from any other component except the LoginForm component seems to work.
Is there anything wrong with my axios call? I just copy/pasted it from a component that works, and it has no issues there.
The method was called on the "Submit" button onClick, which forced the page to reload before the request was completed.
Moving it to the form
<form onSubmit ={(event) => this.loginHandler(event)} >
and adding event as parameter on loginHandler, and this line of code
event.preventDefault();
got it working eventually.

How to fix this function to handle different error type of error catching

I have developing mern stack web site. In that I have added below codes to handle logging.
onSubmit(e) {
e.preventDefault();
const obj = {
user_name: this.state.user_name,
password: this.state.password
};
axios.post('http://localhost:4000/login', obj)
.then(res=> localStorage.setItem('token',(res.data.token))
//localstorage.setItem('username','res.data.user.username)
)
}
When I click on login button this onSubmit() function called and will save token in local storage.
But, res.data have more details. (from backend it passes logged users information too)
So I want to add those to local storage. I tried that as commented in above function. It says error in res. Note : I user react for frontend.
Also I want to handle handle errors in any cases axios.post() didn't work as planned. In server side it send different messages for unmatched credentials and wrong passwords. How can I show those in my page. Thank you.
Since the only accepted data type in localStorage is string, you should stringify it first using JSON API.
const userDataStr = JSON.stringify(res.data);
localStorage.setItem('userData', userDataStr);
Now if you want to access the userData from localStorage you just need to convert it back to javascript object.
const userDataStr = localStorage.getItem('userData', userData);
const userData = JSON.parse(userDataStr);
You can have multiple catch in the returned promise of axios.post
axios.post()
.catch((error) => { })
.catch((error) => { })
But those catch will called with the same error so you need to handle it differently in each catch
Another suggestion:
If you want to easily handle the error, you can use higher order function like this
const handleError = (status, callback) => (error) => {
if (status === error) {
callback(error);
}
}
axios.post()
.catch(handleError(404, (error) => { /* only called when status === 404 */ }))
.catch(handleError(500, (error) => { /* only called when status === 500 */ }))

Resources