React-redux 无法获取用户资料信息。

huangapple go评论54阅读模式
英文:

React-redux cannot get user information for the profile

问题

I am working on an e-commerce project(react, django) and register/login system is working well, but I when I started to work on update profile form, first I decided to get some info of the user. I am getting Authentication credentials were not provided error message.React-redux 无法获取用户资料信息。

In console, I am getting a 401 Unauthorized error: "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 me={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 me={9}>
            <h2>My Orders</h2>
        </Col>
    </Row>
  )
}

export default ProfileScreen
英文:

I am working on an e-commerce project(react, django) and register/login system is working well, but I when I started to work on update profile form, first I decided to get some info of the user. I am getting Authentication credentials were not provided error message.React-redux 无法获取用户资料信息。

In console i am getting a 401 Unauthorized error: "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 me={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 me={9}>
            <h2>My Orders</h2>
        </Col>
    </Row>
  )
}

export default ProfileScreen

答案1

得分: 1

将此更改:
Authorization: 'Bearer'+token,

为:
Authorization: 'Bearer ' + token,

在"Bearer"之后添加空格,然后再次尝试,看看错误是否消失。

英文:

Try change this

before:
Authorization: 'Bearer'+token,

**to: ** Authorization: 'Bearer ' + token,

Add space after "Bearer"
Then, try again and see if the error goes away.

huangapple
  • 本文由 发表于 2023年2月27日 02:58:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75574327.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定