简体   繁体   English

如何使用 axios 在反应中处理状态 401?

[英]how to handle status 401 with axios in react?

i want to check if user is authorized or not, in my AuthContext我想在我的 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>
)
}

and in Auth service i got this:在身份验证服务中我得到了这个:

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

}

i got error Unhandled Rejection (TypeError): Cannot read property 'user' of undefined我收到错误未处理的拒绝(TypeError):无法读取未定义的属性“用户”

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

12 | 12 | AuthService.isAuthenticated() AuthService.isAuthenticated()

13 |.then(data =>{ 13 |.then(数据 =>{

14 | 14 | setUser(data.user);设置用户(数据。用户); // Error // 错误

15 | 15 | setIsAuthenticated(data.isAuthenticated); setIsAuthenticated(data.isAuthenticated);

16 | 16 | setIsLoaded(true); setIsLoaded(true);

17 | 17 | }) })

i test it in postman and i got what i expected我在 postman 中测试它,我得到了我所期望的

Just return the object instead of calling res.json只需返回 object 而不是调用 res.json

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM