React-Redux无法获取用户个人资料信息,报401未授权错误
React+Django电商项目个人资料接口401认证错误排查
我正在开发一个基于React和Django的电商项目,注册登录系统运行正常,但开发更新个人资料表单时,获取用户信息出现Authentication credentials were not provided错误提示。
控制台显示401 Unauthorized错误:"GET /api/users/profile/ HTTP/1.1" 401 58
相关代码片段
userReducers.js
export const userDetailsReducer = (state = { user: {} }, action) =>{ switch (action.type) { case USER_DETAILS_REQUEST: return { ...state, loading: true } case USER_DETAILS_SUCCESS: return { loading: false, user: action.payload } case USER_DETAILS_FAIL: return { loading: false, error: action.payload} default: return state } }
userActions.js
export const getUserDetails = (id) => async (dispatch, getState) => { try{ dispatch({ type: USER_DETAILS_REQUEST }) const { userLogin: { userInfo }, } = getState() const token = userInfo.token const config = { headers:{ 'Content-type': 'application/json', Authorization: 'Bearer'+token, } } const { data } = await axios.get( '/api/users/'+id, config ) dispatch({ type: USER_DETAILS_SUCCESS, payload: data }) }catch(error){ dispatch({ type:USER_DETAILS_FAIL, payload:error.response && error.response.data.detail ? error.response.data.detail : error.message, }) } }
ProfileScreen.js
import React, {useState, useEffect} from 'react' import { Link, useNavigate, useParams, useLocation } from 'react-router-dom' import { Form, Button, Row, Col } from 'react-bootstrap' import { useDispatch, useSelector } from 'react-redux' import Loader from '../components/Loader' import Message from '../components/Message' import { getUserDetails } from '../actions/userActions' function ProfileScreen() { const location = useLocation() const navigate = useNavigate() const [name, setName] = useState('') const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [confirmPassword, setConfirmPassword] = useState('') const [message, setMessage] = useState('') const dispatch = useDispatch() const userDetails = useSelector(state => state.userDetails) const { error, loading, user } = userDetails const userLogin = useSelector(state => state.userLogin) const { userInfo } = userLogin useEffect(() => { if (!userInfo){ navigate('/login') } else { if (!user || !user.name){ dispatch(getUserDetails('profile')) } else { setName(user.name) setEmail(user.email) } } }, [dispatch, navigate, userInfo, user]) const submitHandler = (e) => { e.preventDefault() if(password !== confirmPassword){ setMessage('Passwords do not match') }else{ console.log('Updating...') } } return ( <Row> <Col md={3}> <h2>User Profile</h2> {message && <Message variant='danger'>{message}</Message>} {error && <Message variant='danger'>{error}</Message>} {loading && <Loader/>} <Form onSubmit={submitHandler}> <Form.Group controlId='email'> <Form.Label>Email Address</Form.Label> <Form.Control required type='email' placeholder='Enter Email' value={email} onChange={(e) => setEmail(e.target.value)} > </Form.Control> </Form.Group> <Form.Group controlId='name'> <Form.Label>Name</Form.Label> <Form.Control required type='name' placeholder='Enter Name' value={name} onChange={(e) => setName(e.target.value)} > </Form.Control> </Form.Group> <Form.Group controlId='password'> <Form.Label>Password</Form.Label> <Form.Control type='password' placeholder='Enter Password' value={password} onChange={(e) => setPassword(e.target.value)} > </Form.Control> </Form.Group> <Form.Group controlId='passwordConfirm'> <Form.Label>Confirm Password</Form.Label> <Form.Control type='password' placeholder='Confirm Password' value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} > </Form.Control> </Form.Group> <Button type='submit' variant='primary'>Update</Button> </Form> </Col> <Col md={9}> <h2>My Orders</h2> </Col> </Row> ) } export default ProfileScreen
错误原因与修复方案
核心问题
Authorization请求头格式错误:'Bearer'+token没有在Bearer和token之间添加空格,导致Django后端无法正确解析认证凭证。
修复步骤
修改userActions.js中的Authorization头写法:
Authorization: `Bearer ${token}`,
或者:
Authorization: 'Bearer ' + token,
额外验证点
- 确保
userInfo.token已正确获取到登录后的有效token - 确认Django后端已配置
JWTAuthentication或TokenAuthentication,并对/api/users/profile/接口启用了认证权限
内容的提问来源于stack exchange,提问作者Myrodis
相关产品推荐
相关产品推荐

