admin管理员组文章数量:1410724
So basically I'm making a login function in React and I've made users using api I've stored the users in my MongoDB database and I'm getting no coding errors in my terminal I now have tried to login to one of the accounts and check the console on my browser and I keep getting back the error Cannot read properties of undefined (reading 'data').
Its saying that my console.log(data)
isn't reading any properties and I'd appreciate some help on how i can fix this I'll paste down the code below to show what I've done
I need the console.log(data)
to show the user which I log into information once I've logged in that should appear in the console but the error which I've trying to resolve isn't allowing it
import axios from 'axios';
import React, { useState } from 'react';
import { Col, Container, Row, Form, Button } from "react-bootstrap";
import './Login.css'
export const Login = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
const submitHandler = async (e) => {
e.preventDefault();
try {
const config = {
headers: {
"Content-type": "application/json"
},
};
setLoading(true)
const { data } = await axios.post(
"/api/users/login",
{
email,
password,
},
config
);
//Here is the console.log which isnt returning the users info in my console
console.log(data);
localStorage.setItem('userInfo', JSON.stringify(data));
setLoading(false);
} catch (error) {
setError(error.response.data);
}
};
return (
<Form onSubmit={submitHandler}>
<Form.Group controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control
type="email"
value={email}
placeholder="Enter email"
onChange={(e) => setEmail(e.target.value)}
/>
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
value={password}
placeholder="Password"
onChange={(e) => setPassword(e.target.value)}
/>
</Form.Group>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
);
};
export default Login;
So basically I'm making a login function in React and I've made users using api I've stored the users in my MongoDB database and I'm getting no coding errors in my terminal I now have tried to login to one of the accounts and check the console on my browser and I keep getting back the error Cannot read properties of undefined (reading 'data').
Its saying that my console.log(data)
isn't reading any properties and I'd appreciate some help on how i can fix this I'll paste down the code below to show what I've done
I need the console.log(data)
to show the user which I log into information once I've logged in that should appear in the console but the error which I've trying to resolve isn't allowing it
import axios from 'axios';
import React, { useState } from 'react';
import { Col, Container, Row, Form, Button } from "react-bootstrap";
import './Login.css'
export const Login = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
const submitHandler = async (e) => {
e.preventDefault();
try {
const config = {
headers: {
"Content-type": "application/json"
},
};
setLoading(true)
const { data } = await axios.post(
"/api/users/login",
{
email,
password,
},
config
);
//Here is the console.log which isnt returning the users info in my console
console.log(data);
localStorage.setItem('userInfo', JSON.stringify(data));
setLoading(false);
} catch (error) {
setError(error.response.data);
}
};
return (
<Form onSubmit={submitHandler}>
<Form.Group controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control
type="email"
value={email}
placeholder="Enter email"
onChange={(e) => setEmail(e.target.value)}
/>
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
value={password}
placeholder="Password"
onChange={(e) => setPassword(e.target.value)}
/>
</Form.Group>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
);
};
export default Login;
Share
Improve this question
edited Mar 3, 2022 at 15:37
VLAZ
29.2k9 gold badges63 silver badges84 bronze badges
asked Mar 3, 2022 at 12:04
kazkaz
3512 gold badges3 silver badges7 bronze badges
1
-
"Its saying that my console.log(data) isn't reading any properties" no, it's saying it cannot read
data
ofundefined
. Therefore, the problem is when the code tries to readdata
of something that turns out to beundefined
, not when it tries to usedata
. That would beconst { data } = await axios.post()
which means that the result ofawait axios.post()
isundefined
. – VLAZ Commented Mar 3, 2022 at 15:40
2 Answers
Reset to default 0Try the following, without async/ await.
axios.post("api/users/login", { email, password, },config)
.then(res=>res.data)
.then(data=> {
console.log(data);
localStorage.setItem('userInfo', JSON.stringify(data));
setLoading(false);
})
.catch(error => {
setError(error)
})
I had the same error, in my project I was using axios in an async function with await mand as below (bmUserApi is an api library which I coded myself over axios )
onLogin = async(formValues) => {
this.setState({loading:true, error: ""});
try {
var ls_response = await bmUserApi.login(formValues);
this.setState({loading: false});
const lv_token = ls_response.headers['x-auth-token'];
Redux_Set_User(lv_token, this.props.redux_dispatch, this.props.history);
when I was checking the error position on Google Chrome in "Call Stack" part, I've seen that my api library was trying add to authentication token to the api call header, by reading from localStorage of the browser.
I was doing it by using axios interceptors as below :
axiosClient.interceptors.request.use(
async function(config) {
config.headers = {
'Content-Type': 'application/json'
}
// token :
var ls_user = JSON.parse(localStorage.getItem('user'));
const authToken = ls_user.token;
if (authToken)
config.headers['x-auth-token'] = authToken;
return config;
},
error => { Promise.reject(error) }
)
But this is login call .. so off course there is no stored data and token on the browser yet. So the "ls_user" variable in the above code was null .. this was causing the error. I just added control before that.
I hope this can be useful to your case.
本文标签:
版权声明:本文标题:javascript - TypeError: Cannot read properties of undefined (reading 'data') console.log(data) isnt returning us 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745010401a2637518.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论