Unable to retrieve API data using axios - reactjs

I'm trying to build a simple login using an API but keep facing errors
import React from "react";
import { useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
export default function Login() {
const navigate = useNavigate();
const [formData, setFormData] = useState({
uid: "",
password: "",
blocked: 0
});
const handleSubmit = (e) => {
e.preventDefault();
console.log(formData);
const data = JSON.stringify(formData);
console.log(data);
axios
.post("https://myphysio.digitaldarwin.in/api/login/", data)
.then(function (response) {
console.log(response);
console.log("Successfully Logged in ");
navigate("/success");
})
.catch(function (error) {
console.log(error);
});
};
return (
<form onSubmit={handleSubmit}>
<h3>Login</h3>
<div className="form-group">
<label>uid Name</label>
<input
name="uid"
className="form-control"
placeholder="Enter your uid Name"
value={formData.uid}
onChange={(e) => setFormData({ ...formData, uid: e.target.value })}
/>
</div>
<div className="form-group">
<label>Password</label>
<input
type="password"
name="password"
className="form-control"
placeholder="Enter password"
value={formData.password}
onChange={(e) =>
setFormData({ ...formData, password: e.target.value })
}
/>
</div>
<button type="submit" className="btn btn-primary btn-block">
Submit
</button>
</form>
);
}
The error I keep facing is
console log of error
POST https://myphysio.digitaldarwin.in/api/login/ 500 (Internal Server Error)
Error: Network Error
at createError (createError.js:16:1)
at XMLHttpRequest.handleError (xhr.js:117:1)
POST https://myphysio.digitaldarwin.in/api/login/ net::ERR_CONTENT_LENGTH_MISMATCH 500 (Internal Server Error)

All your errors come from the backend so I suggest you to post a question in the django section (I looked at the link and I was django framework so I assume that you use django). Maybe you don't want to stringify your formData (usually it's common to send a json in a post request).

Related

How to display data from an API in react js?

Here I have a login form that I created in react js. The API I'm using gives a response as "Successful Login" or "Authentication Failed. Unable to login" depending on whether the login credentials match or not. In the login form I'm using a react hook and axios.post to send the "name" and "password" to the API. How can I also print the response I'm getting back from the API?
Here is the Login.js component:
import React, { Component } from "react";
import { useState, useEffect } from "react";
import axios from "axios";
import { Button, TextField } from "#mui/material";
class Login extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
password: "",
};
}
changeHandler = (e) => {
this.setState({ [e.target.name]: e.target.value });
};
submitHandler = (e) => {
e.preventDefault();
console.log(this.state);
axios
.post("http://localhost:8080/users/login", this.state)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
};
render() {
const { name, password } = this.state;
return (
<div>
<h1>Login Page</h1>
<form onSubmit={this.submitHandler}>
<TextField
name="name"
label="Enter Username"
color="secondary"
focused
size="small"
variant="outlined"
onChange={this.changeHandler}
id="name"
value={name}
type="text"
placeholder="Username"
className="form-control"
/>
<p />
<TextField
name="password"
label="Enter Password"
color="secondary"
focused
size="small"
variant="outlined"
onChange={this.changeHandler}
id="password"
value={password}
type="text"
placeholder="Password"
className="form-control"
/>
<p />
<Button type="submit" variant="contained">
Login
</Button>
</form>
</div>
);
}
}
export default Login;
And here is what the console shows:
{name: 'Mike', password: 'password1234'}
{data: 'Authentication Failed. Unable to login', status: 200, statusText: '', headers: AxiosHeaders, config: {…}, …}
{name: 'Mike', password: 'Pass1234'}
{data: 'Successful Login', status: 200, statusText: '', headers: AxiosHeaders, config: {…}, …}
Can I use another react hook to fetch the data? The API uses POST method so I'm not sure how to do that.
here is a very basic example of login page using hooks. In the login function, you should call the API you want and use the setResponse to display the response on the screen
const [Name, setName] = useState("");
const [Pass, setPass] = useState("");
const [Response, setResponse] = useState("");
const userChange = (event) => {
setName(event.target.value);
};
const passChange = (event) => {
setPass(event.target.value);
};
const login = () => {
// login using Name and Pass
setResponse("server response")
}
return (
<ThemeComponent>
<TextField label={"user"} onchange={userChange} />
<TextField label={"pass"} onchange={passChange} />
{Response}
<Button onClick={login} text="LOGIN">LOGIN</Button>
</ThemeComponent>
)

i want to show details on same page

i am developing an application i.e supply chain management application on reactJS, NodeJS and blockchain.
Frontend code:
import React, { Component } from 'react'
import { useState, useEffect } from "react";
import axios from "axios";
import { useNavigate } from 'react-router-dom';
const SignUp = () => {
const navigate = useNavigate();
const flag=0;
const [data, setData] = useState({
uname: "",
email: "",
location: "",
budget: "",
password: ""
});
const handleChange = (e) => {
const value = e.target.value;
setData({
...data,
[e.target.name]: value
});
};
const handleSubmit = (e) => {
e.preventDefault();
const userData = {
uname: data.uname,
email: data.email,
location: data.location,
budget: data.budget,
password: data.password
};
axios
.post("http://localhost:8080/api/signup/", userData)
.then((response) => {
console.log(response);
})
.catch((error) => {
if (error.response) {
console.log(error.response);
console.log("server responded");
} else if (error.request) {
console.log("network error");
} else {
console.log(error);
}
});
navigate(`/home`)
};
return (
<form>
<h3>Sign Up</h3>
<div className="mb-3">
<label>User Name</label>
<input
type="text"
name="uname"
value={data.uname}
className="form-control"
placeholder="User name"
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Email address</label>
<input
type="email"
name="email"
value={data.email}
className="form-control"
placeholder="Enter email"
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Location</label>
<input
type="text"
name="location"
value={data.location}
className="form-control"
placeholder="Location"
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Budget</label>
<input
type="Number"
name="budget"
value={data.budget}
className="form-control"
placeholder="Budget"
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Password</label>
<input
type="password"
name="password"
value={data.password}
className="form-control"
placeholder="Enter password"
onChange={handleChange}
/>
</div>
<div className="d-grid">
<button type="submit" onClick={handleSubmit}className="btn btn-primary">
Sign Up
</button>
</div>
<p className="forgot-password text-right">
Already registered sign in?
</p>
</form>
);
};
export default SignUp;
here if user successfully registered then i want to show deatils of the user on the same page. how should i do that?
i have attached the code and the screenshot of the page.
currently i am on my account page.
Inside of your handle submit
You can just navigate after the axios.then callback
Or if you want the behavior to be that user submits -> register success -> show success -> then redirect, you can setTimeout for say 1000ms and then navigate.
axios
.post("http://localhost:8080/api/signup/", userData)
.then((response) => {
console.log(response);
})
.then(() => {
setTimeout(() => navigate(`/home`), 1000);
}
.catch((error) => {
if (error.response) {
console.log(error.response);
console.log("server responded");
} else if (error.request) {
console.log("network error");
} else {
console.log(error);
}
});
If you mean, show the user data after a successful registration and assuming you're calling an api to register the user and you're getting the user details back on success, you can handle that in your handleSubmit method.
Here's an example
const showUserDetails = (userDetails) => {
// Code that shows user details
// Probably using state
};
const handleSubmit = (e) => {
e.preventDefault();
const userData = {
...
axios
.post("http://localhost:8080/api/signup/", userData)
.then((response) => {
// handle here
showUserDetails(response);
})
.catch((error) => {
if (error.response) {
...
} else {
console.log(error);
}
});
};

I can't find an example of how to make an HTTP POST request using useEffect hook along with axios

Lately, I've been trying to make an HTTP POST request using the useEFfect hook along with axios, but the code returns this error in the console: Error: Request failed with status code 422. The POST request is always successfully made when I make it from the form onSubmit handler. However, when I try to make it from the useEffect hook, it gives that error. Can anybody help me with what I'm doing wrong? Here's the code:
import React, { useState, useEffect } from "react";
import axios from "axios";
function RandomPost() {
const [input, setInput] = useState({
name: "",
email: "",
companyName: "",
password: "",
});
const handleChange = (event) => {
setInput({ ...input, [event.target.id]: event.target.value });
};
const handleSubmit = (e) => {
e.preventDefault();
};
useEffect(() => {
const { name, email, companyName, password } = input;
axios
.post(`https://01hire.collaq.com/user/createCompany`, input)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
}, [input]);
const { name, email, companyName, password } = input;
return (
<div>
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" id="name" value={name} onChange={handleChange} />
</label>
<label>
Email:
<input type="text" id="email" value={email} onChange={handleChange} />
</label>
<label>
Company Name:
<input
type="text"
id="companyName"
value={companyName}
onChange={handleChange}
/>
</label>
<label>
Password:
<input
type="password"
id="password"
value={password}
onChange={handleChange}
/>
</label>
<button type="submit">Submit</button>
</form>
</div>
);
}
export default RandomPost;

Submit formData with Reactjs doesn't work

I'm trying to use formData() to submit a login form using Reactjs and Hooks, but it doesn't work.
Values returned from the formData components seem to be correct. I have try it both with Axios and Fetch and none of them work.
I have also tried different ways of populating the formData element, even with fixed strings, but none of them work.
I'm sure I'm making some naive mistake but, I can't find it.
Could some of you help me please?
Thank you
import React, {useState} from 'react'
import axios from 'axios'
function useLoginForm() {
const [field, setField] = useState({email: '', password: ''})
const changeHandler = (event) => {
setField({...field, [event.target.name]: event.target.value})
}
const onBlurHandler = (event) => {
setField({...field,[event.target.name]: event.target.value});
}
const fileHandler = (event) => {
console.log(event.target.files[0])
}
const submitHandler = async (event) => {
event.preventDefault();
for(let [name, value] of loginFormData) {
console.log(`KEY: ${name} VALUE = ${value}`);// Logging outcome details
}
const url = 'https://my_url/post'
}
console.log(`Submit --> ${field.email} - Password ${field.password}`);
try{
const response = await axios.post(url, loginFormData,{
headers: {
"Content-type": "multipart/form-data" /* ; boundary=${loginFormData._boundary}*/
},
}
)
console.log(response.data)
}catch(error){
console.log(error)
}
}
return (
<div>
<p>{field.email} - {field.password}</p>
<form id="loginForm" name="loginForm" onSubmit={submitHandler}>
<label htmlFor="email">email</label>
<input type="text" name="email" id="email" onChange={changeHandler} /* onBlur={onBlurHandler} */></input>
<label htmlFor="password">Password</label>
<input type="password" name="password" onChange={changeHandler} /* onBlur={onBlurHandler} */></input>
<input type="submit" value="Login" />
</form>
</div>
)
}
export default useLoginForm
Results:
KEY: email VALUE = xyz_xyz#VBM.com useLoginForm.js:47
KEY: password VALUE = Xxxxxx useLoginForm.js:47
Submit --> xyz_xyz#VBM.com - Password Xxxxxx useLoginForm.js:57
XHRPOSThttps://my_url/post
[HTTP/1.1 404 Not Found 6681ms]
1
-----------------------------345147470230284216993885766804
2
Content-Disposition: form-data; name="email"
3
4
xyz_xyz#VBM.com
5
-----------------------------345147470230284216993885766804
6
Content-Disposition: form-data; name="password"
7
8
Xxxxxx
9
-----------------------------345147470230284216993885766804--
10

Set state on form submit in a functional component

In my react typescript app - I have a login component and a handleLoginRequest function which sets the userMessage value:
function Login() {
let [userMessage, setUserMessage] = useState("");
return (
<form className="form-inline" onSubmit={(e) => {
setUserMessage(handleLoginRequest(e))
}} >
<label className="mr-sm-2">Email address:</label>
<input type="email" className="form-control mb-2 mr-sm-2" placeholder="Enter email" id="email" />
<label className="mr-sm-2">Password:</label>
<input type="password" className="form-control mb-2 mr-sm-2" placeholder="Enter password" id="password" />
<button type="submit" className="btn btn-primary mb-2">Submit</button>
{userMessage}
</form>
);
}
Update: handleLoginRequest is a API request
const handleLoginRequest = (event: any): any => {
event.preventDefault();
const data = {
email: event.target.email.value,
password: event.target.password.value
};
axios.post(`${process.env.REACT_APP_HTTP_PROXY}/api/v1/login`, data)
.then(res => {
console.log(res.data);
return res.data;
})
.catch(err => {
console.log(err);
return err.message;
});
}
Expected behavior:
When the form is submitted, the function setUserMessage(handleLoginRequest(e)) is called. I expect that it update the value of userMessage to login request received.
Actual result:
No change in the value of userMessage
What is the fix here?
Updated answer per the question modification
The issue is stemming from the fact you're trying to setState based on a axios post request. Axios requests are asynchronous, meaning they will happen out of order with the program control flow. Therefore, to solve this issue, it is important you only make a call to setUserMessage when the request is complete.
Example Code:
axios.post(`${process.env.REACT_APP_HTTP_PROXY}/api/v1/login`, data)
.then(res => {
setUserMessage(res.data);
})
.catch(err => {
// Do Something with error response
setUserMessage("Error: Something with the request went wrong.");
});
I will link a codesandbox to demonstrate:
https://codesandbox.io/s/focused-leakey-0jer4

Resources