用户在身份验证后尝试执行“获取获取”请求时获取401错误

时间:2020-10-25 05:56:48

标签: reactjs react-native expo

我试图在掠过用户后获得用户详细信息,但是即使用户以200 ok掠过用户,也会遇到401错误。

  • 过程说明:
  • 我已使用获取帖子请求登录用户。
  • 存储的用户名,角色,staffid到异步存储
  • 现在我想用获取请求列出所有用户(端点响应使用/api/staff抛出用户的名字和姓氏),但是每当我发出GET请求时 引发401错误。 谢谢您,这将是挽救生命的第一步!

这是我的代码

import AsyncStorage from "@react-native-community/async-storage";
import React, { useState, useEffect } from "react";

import { SafeAreaView, Text, StyleSheet, Alert } from "react-native";
import AuthService from "../api/auth-service";
import BASE_URL from "../api/baseUrl";

export default function HomeScreen(props) {
  const [firstName, setFirstName] = useState({});
  const [lastName, setLastName] = useState({});

  const [userValue, setUserValue] = useState({});

  useEffect(() => {
    let mounted = true;
    if (mounted) {
      getDataFromStorage();
      getUserInfo();
    }
    return () => {
      mounted = false;
    };
  }, []);

  const getDataFromStorage = async () => {
    let user = await AsyncStorage.getItem("LoggedInUser");
    setUserValue(JSON.parse(user));
  };

       const getUserInfo=async()=>{
  return fetch(BASE_URL+"/api/staff")
  .then((response) => { 
    if(response.ok){
    console.log(response);
    }else{
      console.log(response.status);
      
    }
  })
  .catch((error) => {
    console.log(error);
    this.setState({ errorMsg: "Error retreiving data" });
  });
}

 return (
    <SafeAreaView>
      <Text>
        {"Good morning " + userValue.username + "  "}
        {"you role is  " + userValue.role +"your staff id is " + userValue.staffId+" " + "your first name is "+ firstName +"this is your last name"+lastName} 
      </Text>
    </SafeAreaView>
  );
}

authservice.js

import AsyncStorage from "@react-native-community/async-storage";
import BASE_URL from "./baseUrl";

class AuthService {
  login(Username, Password, role) {
    console.log(Username, role);

    return fetch(BASE_URL + "/api/authentication/login", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      
      body: JSON.stringify({
        Username,
        Password,
      }),
    }).then((res) => {
      if (res.ok) {
        console.log("the login response", res);
        return res.json();
      } else {
        alert("Invalid Username or Password");
        window.stop();
      }
    });
  }

  logout() {
    AsyncStorage.getAllKeys().then((keys) => AsyncStorage.multiRemove(keys));
      }
}
export default new AuthService();

login.js

const submitData = async () => {
 AuthService.login(Username, Password).then(
      (data) => {
        console.log(JSON.stringify(data));
        AsyncStorage.setItem("LoggedInUser", JSON.stringify(data));
        if (data.role == "Admin") {
          console.log(data.username);
          navigation.navigate("adminPage");
        } else {
          navigation.navigate("staffpage");
        }
      },
      (error) => {
        Alert.alert(error);
      }
    );
  };

3 个答案:

答案 0 :(得分:0)

根据developer.mozilla.org

HTTP 401未经授权的客户端错误状态响应代码表示该请求尚未应用,因为它缺少针对目标资源的有效身份验证凭据。

似乎用户没有访问API的权利。确保getUserInfo()API / api / staff在HTTP请求的标头中不需要任何身份验证令牌。

答案 1 :(得分:0)

我觉得您可能还需要在AuthService.login中解决另一个诺言。

res.json()实际上是一个承诺,也需要解决,因此您可能还需要一个then块,如下所示:

return fetch(BASE_URL + "/api/authentication/login", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      
      body: JSON.stringify({
        Username,
        Password,
      }),
    }).then((res) => {
      if (res.ok) {
        console.log("the login response", res);
        return res.json();
      } else {
        alert("Invalid Username or Password");
        window.stop();
      }
    }).then(finalData=>finalData )// <---------- add this
      .catch(err=> err) 

答案 2 :(得分:0)

发生这种情况是因为getDataFromStorage是一个异步函数,因此您必须首先解决它。同样在login.js中,我们必须等待导航才能确保数据已保存在AsyncStorage中。请更新代码的以下部分:

login.js

const submitData = async () => {
 AuthService.login(Username, Password).then(
      async (data) => {
        console.log(JSON.stringify(data));
        await AsyncStorage.setItem("LoggedInUser", JSON.stringify(data));
        if (data.role == "Admin") {
          console.log(data.username);
          navigation.navigate("adminPage");
        } else {
          navigation.navigate("staffpage");
        }
      },
      (error) => {
        Alert.alert(error);
      }
    );
  };

接下来,将userValue初始化为空

const [userValue, setUserValue] = useState(null);

现在有2个useEffect,

useEffect(() => {
  let mounted = true; //Why this required as it doesn't mean anything
  if (!userValue) {
    getDataFromStorage();
  }
  return () => {
    mounted = false;
  };   
}, []);
useEffect(()=>{
  if(userValue){
    getUserInfo()
  }
},[userValue])