how to catch api resonse data in react js - javascript

i have one project in spring boot where i have created one API login.where i am sending user name and password with this API .if data is present in database it is returning login successfully if not then it is returning login fail.in react i have to text filed and i am storing that data.now i want to call login API in react with saved text field value and if login successfully then i want to save that response or that returned value in react it may be login successfully or all user details or show that response in react.please anyone help

Use Error handling function
try{
//Call your API here
}
catch(){
//Error handles here
}
finally{
//Executes anyway
}

You have to save your response in state then show it on frontend
import axios from 'axios';
const [loginData, setLoginData] = useState([]);
const onSubmit = async (e) => {
e.preventDefault();
try {
const requestBody = {
emailAddress: email,
password: password,
}
axios.post(`${config.url.API_URL}${BASE_URL.Auth_BASE_URL}/login`, requestBody)
.then(response => {
if (response) {
setLoginData(response);
console.log("Login success");
} else {
console.error("Login fail");
}
}).catch(function (error) {
console.log(error);
});
} catch (err) {
console.log(err);
}
}

Related

How to make a post request by SERVER not by user

Node.js CODE
exports.user = async (req, res) => {
try {
const { wallet } = req.body;
if (!wallet) {
res.status(400).json({ error: "Not logged in" });
return;
} else {
user = User.findone(wallet);
// if user is not found then create a new user and mark as loggged In
if (!user) {
User.create({
user: wallet,
});
}
// if user found then create a session token and mark as logged
in
res.send({
user: wallet,
});
}
} catch (error) {
console.log(`ERROR::`, error);
}
};
REACTJs CODE
// post call/update
const axiosCall = async () => {
// core login will give a unique username by fulling a transcation
// core.login i dont have any control
const userAccount = await core.login();
try {
const res = await Axios.post(`${API}/user`, userAccount, dataToken);
setData({
...data,
error: "",
success: res.data.message,
});
} catch (error) {
setData({
...data,
error: error.response.data.error,
});
}
};
Now here the problem occurs when some one could modify userAccount in the front-end or someone could send a body with wallet: anything to my route localhost:3000/api/user
There is no option for me to check if some actually used core.login(); to get the wallet address.
So is there any solution?
I was thinking to allow only my server IP or localhost to hit the route localhost:3000/api/user and is that even possible?
Also there is another issue anyone could modify userAccount in front-end.

Error , Console log the axios network response

1.I'm working on an backend API but at some point I need to get user data from another API. I am trying to use Axios to make http request in order to do that. The request return the result in the browser as expected but the problem is that I can't display console log in the terminal. It doesn't show anything even though I asked the program to do so. Is there a problem probably with my code?
2.Error message =>>> POST http://localhost:8000/api/register 400 (Bad Request) Error: Request failed with status code 400`
const handleSubmit = async () => {
//e.preventDefault();
try
{
// console.log(name, email, password, secret);
const { data } = await axios.post("http://localhost:8000/api/register", {
name,
email,
password,
secret,
});
setOk(data.ok); //useState component
}
catch (error) {
**strong text**
console.log(error.response.data);
}
}
import User from '../models/user'
//import{ hashPassword, comparePassword } from '../helpers/auth'
export const register = async (req,res) => {
//console.log('Register endpoint =>', req.body)
//to make this work make express.json is applied in the above middleware
//console.log error to debug code
const {name, email, password, secret} = req.body;
//validation
if(!name) return res.status(400).send('Name is required')
if(!password || password.length < 6) return res.status(400).send('Password is
short
or password is not entered')
if(!secret) return res.status(400).send('Answer is required')
//The above code is for validation purpose to make sure data is correctly
entered
const exist = await User.findOne({email })
if(exist) return res.status(400).send('Email is taken')
}
.catch(error => {
console.log(error)
})
May be catching error on your axios is wrong try this

Async storage cannot retrieve data from react native

I am using AsyncStorage to keep user data to phone. After registering the user, i am trying to retrieve the user if exist one and automate redirect to profile page.
but I have problems with async storage because it returns only the word 'user' in the console...
in the login component ->
import AsyncStorage from '#react-native-async-storage/async-storage';
const loggedUser = async () => {
try {
const u = await AsyncStorage.getItem('user');
console.log(u);
} catch (error) {
console.log(error);
}
};
/**
*
* This function retrieve the data from the server and store it to the local database..
*
*/
const executeLogin = async (email, password) => {
try
{
// Get data and store in async storage
const response = await data.post('/api/login', {email, password});
storeData('user', response.data); -> //Check the code bellow for the source
}
// Catch all errors bellow
catch (error)
{
if (error.response.status === 404 && error.response.data === 'Wrong credentials') {
Alert.alert('Whoops!', 'You entered the wrong credentials. Please try again.');
}
else {
Alert.alert('Whoops!', 'Something went wrong. This is an unexpecred error. We will try to fix it as soon as possible');
}
}
};
export default executeLogin;
The code block above calls the axios and supose to store the data to async storage. But I have no ideea also if it worked because it gave me no error...
import AsyncStorage from '#react-native-async-storage/async-storage';
/**
*
* This function must only accept serialised object with JSON.stringfy() method
*
*/
const storeData = async object => {
try
{
await AsyncStorage.setItem('user', object);
}
catch (error)
{
console.log(error);
}
}
export default storeData;
This is the store function
Cannot understand what I am doing wrong....
Thanks, Daniel

How to call api using fetch in React native

const login: SubmitHandler<ILoginValues> = async ({email, password}) => {
try {
const res = await fetch(`${config.apiUrl}/api/login`, {
method: 'POST',
body: JSON.stringify({
email,
password,
}),
});
if (res.ok) {
await setGenericPassword(email, password, CREDENTIALS_STORAGE_OPTIONS);
setUser({isLoggedIn: true, hasSessionExpired: false});
}
} catch (error) {
toast.setToast({message: 'Login failed', visible: true});
}
};
I am creating a login flow in react native using java spring rest api. My Api is running at address http://localhost:8082/api/v1/users how can I get the data from client side using fetch in React native and also store the JWT token in client side.
You can perform the login request when the form is submitted. Than wait for the response and save the jwt in local storage. Than login the user into the logged in ui.
const form = document.getElementById("form-id")
form.addEventListener("submit", async (e) =>{
e.prevetDefault() your code })

login user data does not persist once I refresh

Hi I am using express for backend authentication and these are my sign in functions/controllers on the front end.
export const signInUser = async credentials => {
console.log('this is for the signInUser', credentials)
try {
const resp = await api.post('/sign-in', credentials)
localStorage.setItem('token', resp.data.token)
return resp.data
} catch (error) {
throw error
}
}
onSignIn = event => {
event.preventDefault()
const { history, setUser } = this.props
signInUser(this.state)
.then(res => setUser(res.user))
.then(() => history.push('/Home'))
.catch(error => {
console.error(error)
this.setState({
loginUsername: '',
loginPassword: '',
})
})
}
setUser = user => this.setState({ user })
and this is my sign in controller on the backend
const signIn = async (req, res) => {
try {
console.log('hello' ,req.body);
const { loginUsername, username, loginPassword } = req.body;
const user = await User.findOne({
where: {
username: loginUsername
}
});
console.log('this is the user', user)
if (await bcrypt.compare(loginPassword, user.dataValues.password_digest)) {
const payload = {
id: user.id,
username: user.username,
password: user.password
};
const token = jwt.sign(payload, TOKEN_KEY);
return res.status(201).json({ user, token });
} else {
res.status(401).send("Username or Password is invalid- try again.");
}
} catch (error) {
return res.status(500).json({ error: error.message });
}
};
The issue is the state of the user doesn't persist on refresh but I still have the json webtoken in my local storage and this is an issue when I make post requests and even signing up since I am redirecting to the home page and losing the user state. Any help would be appreciated!
From your tags, I noticed that you are using React, so the solution is simple!
you can have an GlobalAuthManager context for your application that would wrap all the components at the most higher level! after <React.strictMode> like below:
<React.StrictMode>
<GlobalAuthManager.Provider value={{authData}}>
<App />
</GlobalAuthManager.Provider>
</React.StrictMode>
As you might guess, this would be a context! that would provide you your user data to all your components!
The Pattern:
1. Store token:
when your user logins to your app, you would receive a token ( in your response or in response header ), you need to store the token value in localstorage, or more better in cookie storage (there are a lot of articles about it why), one is here.
2. have a /getUserData endpoint in backend:
you need to have a /getUserData endpoint in backend to retrive your user data based on token
3. call /getUserData in app mount:
before every thing in your app, you need to call this endpoint if you find token in localstorage or cookie storage. so if you run this in your componnetDidMount or useEffect(() => { ... }, []), that would work!
4. store your user data and state in context:
after you've called the /getUserData and if you had a valid token(i mean not expired token or not interrupted and edited token) , you will get you user data and what you need to do is that you need to store this in your GlobalAuthManager and provide that in to your Global App component!
after that you have your user data available to you that you can decide to show login or sign up button in your Navbar or disable/enable comment section for example based on your user data!
Wrap up:
So the key is that you have to have a GlobalAuthManager for only one purpose, that before every thing it runs in the top level in your app and gets you your user data based on provided token from localstorage or cookie storage!
after that you can manage your app state based on that your user is logged in or not!

Categories