axios请求失败?

Posted

技术标签:

【中文标题】axios请求失败?【英文标题】:Axios request failed? 【发布时间】:2020-11-26 06:58:00 【问题描述】:

如果我尝试使用此令牌授权它,我已经使用 react redux 从登录中获取令牌。错误是显示Axios request failed: TypeError: Cannot read property 'token' of undefined 我想用令牌授权它。令牌存储在本地存储中,但是当我使用(Token $props.token 时它无法授权它,如果我尝试这种方式(Token 5302f4340a76cd80a855286c6d9e0e48d2f519cb 那么我的 AritcleList.js 已授权它

这里是 react-redux 认证

authAction.js

    import axios from 'axios';
    import * as actionTypes from './actionTypes';

    export const authStart = () => 
        return 
            type: actionTypes.AUTH_START
        
    

    export const authSuccess = token => 
        return 
            type: actionTypes.AUTH_SUCCESS,
            token: token
        
    

    export const authFail = error => 
        return 
            type: actionTypes.AUTH_FAIL,
            error: error
        
    

    export const logout = () => 
        localStorage.removeItem('token');
        return 
            type: actionTypes.AUTH_LOGOUT
        ;
    



    export const authLogin = (userData) => 
        return dispatch => 
            dispatch(authStart());
            axios.post('http://localhost:8000/rest-auth/login/', userData)
                .then(res => 
                    const token = res.data.key;
                    localStorage.setItem('token', token);
                    dispatch(authSuccess(token));
                )
                .catch(err => 
                    dispatch(authFail(err))
                )
        
    

authReducer.js

    import * as actionTypes from '../actions/actionTypes';
    import  updateObject  from '../utility';

    const initialState = 
        isAuthenticated: null,
        token: null,
        error: null,
        loading: false
    

    const authStart = (state, action) => 
        return updateObject(state, 
            isAuthenticated: false,
            error: null,
            loading: true
        );
    

    const authSuccess = (state, action) => 
        return updateObject(state, 
            isAuthenticated: true,
            token: action.token,
            error: null,
            loading: false
        );
    

    const authFail = (state, action) => 
        return updateObject(state, 
            error: action.error,
            loading: false
        );
    

    const authLogout = (state, action) => 
        return updateObject(state, 
            token: null
        );
    

    export default function (state = initialState, action) 
        switch (action.type) 
            case actionTypes.AUTH_START: return authStart(state, action);
            case actionTypes.AUTH_SUCCESS: return authSuccess(state, action);
            case actionTypes.AUTH_FAIL: return authFail(state, action);
            case actionTypes.AUTH_LOGOUT: return authLogout(state, action);
            default:
                return state;
        
    

articleList.js

    import React,  useState, useEffect  from 'react';
    import  Container, Row, Col  from 'react-bootstrap';
    import Card from '../components/Card'
    import FullPageLoader from "../components/FullPageLoader";
    import axios from 'axios';
    import  connect  from 'react-redux'

    const NewsList = () => 
        const [items, setItems] = useState([])
        const [isLoading, setLoading] = useState(true)
        const [isAuthenticated, setAuth] = useState(true); //i don't know how to authenticate it when i also login

        useEffect((props) => 
            const fetchItems = async () => 
                try 
const config = 
                    headers: 
                        'Content-Type': 'application/json',
                        Authorization: `Token $props.token`
                    
                
                    const res = await axios.get(`$process.env.REACT_APP_API_URL/api/`, config);
                    setItems(res.data)
                    setLoading(false);
                
                catch (err) 
                    console.log(`???? Axios request failed: $err`);
                
            
            fetchItems()
        )
        , [items]);
        return (
            <Container className="mt-5">
                < div className="bread-header" >
                    <h5>Dashboard</h5>
                </div >
                <hr />
                <Row>
                    <Col sm=8>
                        
                            isLoading ? <FullPageLoader /> :
                                <div>
                                    itemData.map((item, index) => (
                                        <Card key=index item=item isAuthenticated=isAuthenticated ></Card>
                                    ))
                                </div>
                        
                    </Col>
                </Row>
            </Container >
        )
    

    const mapStateToProps = (state) => 
        return 
            isAuthenticated: state.auth.token,
        
    
    export default connect(mapStateToProps)(NewsList)

【问题讨论】:

调用 API 得到了什么响应? 我的问题更新了! 【参考方案1】:

看看这个帖子:Sending the bearer token with axios

您需要将令牌作为标头添加到请求中。

【讨论】:

以上是关于axios请求失败?的主要内容,如果未能解决你的问题,请参考以下文章

Nuxt + Axios 作为插件请求失败 404

React Native axios 总是返回“请求失败,状态码 400”

Axios 请求错误 - 消息序列化失败(无效编码)

Angular http post 请求失败,但 axios 1 有效

记录一次axios请求造成的数组初始化失败

Axios GET请求在我的本地版本上运行,但在Heroku上失败-未捕获(承诺)错误:请求失败,状态码为500