类型错误:无法读取未定义(读取"数据")控制台的属性.log(数据)不返回用户信息



所以,基本上我在React中创建了一个登录功能,并使用api创建了用户。我已将用户存储在MongoDB数据库中,我的终端中没有出现编码错误。我现在已尝试登录到其中一个帐户并检查浏览器上的控制台,我不断返回错误Cannot read properties of undefined (reading 'data').

据说我的console.log(data)没有读取任何属性,我很感激有关如何修复此问题的帮助。我将粘贴下面的代码,以显示我所做的

我需要console.log(data)向用户显示我登录后应该出现在控制台中的信息,但我试图解决的错误不允许它

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;

尝试以下操作,不使用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)
})

我也有同样的错误,在我的项目中,我在异步函数中使用axios,并使用如下的await命令(bmUserApi是一个api库,我通过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);   

当我在"谷歌浏览器"中检查错误位置时;调用堆栈";部分,我看到我的api库试图通过从浏览器的localStorage读取内容,将身份验证令牌添加到api调用头中。

我是通过使用axios拦截器来做到这一点的,如下所示:

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

但这是登录呼叫。。当然,浏览器上还没有存储数据和令牌。因此;ls_user";上面代码中的变量为null。。这是导致错误的原因。我只是在那之前添加了控制。

我希望这对你的案子有用。

最新更新