【问题标题】:how to handle status 401 with axios in react?如何在反应中使用axios处理状态401?
【发布时间】:2020-12-07 10:02:51
【问题描述】:

我想在我的 AuthContext 中检查用户是否被授权

import React, {createContext,useState,useEffect} from 'react';
import AuthService from '../Services/AuthService';
export const AuthContext = createContext();
export default ({ children })=>{
const [user,setUser] = useState(null);
const [isAuthenticated,setIsAuthenticated] = useState(false);
const [isLoaded,setIsLoaded] = useState(false);

useEffect(()=>{
    AuthService.isAuthenticated()
    .then(data =>{
        setUser(data.user);
        setIsAuthenticated(data.isAuthenticated);
        setIsLoaded(true);
    })
    
},[]);

return (
    <div>
        {!isLoaded ? <h1>Loading</h1> : 
        <AuthContext.Provider value={{user,setUser,isAuthenticated,setIsAuthenticated}}>
            { children }
        </AuthContext.Provider>}
    </div>
)
}

在身份验证服务中我得到了这个:

const Axios = require("axios");
export default{

isAuthenticated : ()=>{
    return  Axios({
        url: "http://localhost:4000/user/authenticated",
        method: "GET",
        
    }).then(res=>{
                if(res.status !== 401)
                    return res.json().then(data => data);
                else
                    return res.json({
                        isAuthenticated : false, 
                        user:{
                            firstName:" ",
                            lastName:" ",
                            email:" "}});
            })
      .catch(err=>console.log("authenticated error :"+err));
}

}

我收到错误 Unhandled Rejection (TypeError): Cannot read property 'user' of undefined

11 |使用效果(()=>{

12 | AuthService.isAuthenticated()

13 | .then(数据 =>{

14 |设置用户(数据。用户); // 错误

15 | setIsAuthenticated(data.isAuthenticated);

16 | setIsLoaded(true);

17 | })

我在邮递员中测试它,我得到了我的预期

【问题讨论】:

    标签: node.js reactjs axios


    【解决方案1】:

    只返回对象而不是调用 res.json

                    return {
                        isAuthenticated : false, 
                        user:{
                            firstName:" ",
                            lastName:" ",
                            email:" "}};
    

    【讨论】:

    • 我遇到了同样的错误:无法读取未定义的属性“用户”
    • Console.log(data) 上面的 setUser(data.user);查看对象的外观。也许你需要做 data.data.user
    • 我得到了数据:未定义
    猜你喜欢
    • 2020-09-10
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 2020-05-13
    • 2011-05-20
    • 2017-05-02
    相关资源
    最近更新 更多