尝试创建新帖子时遇到401错误

时间:2019-12-19 06:19:46

标签: react-native

我正在尝试使用内置于react native的应用创建帖子,但是每次登录后,每次尝试创建它都会给我401错误。我认为它没有从AsyncStorage获取令牌。我需要帮助

这是ItemContext,用于创建帖子的功能

import createDataContext from "./createDataContext";
import sellerApi from "../api/seller";
import { navigate } from "../navigationRef";

const itemReducer = (state, action) => {
  switch (action.type) {
    case "fetch_items":
      return action.payload;
    case "create_item":
      return { errorMessage: "", item: action.payload };
    default:
      return state;
  }
};

const fetchItems = dispatch => async () => {
  const response = await sellerApi.get("/api/items");
  console.log(response.data);
  dispatch({ type: "fetch_items", payload: response.data });
};

const createItem = dispatch => async (
  title,
  category,
  detail,
  condition,
  price
) => {
  try {
    const response = await sellerApi.post("/api/items", {
      title,
      category,
      detail,
      condition,
      price
    });
    //this is the other place the error might be happening i need this to save in the phone local storage
    console.log(response.data);
    dispatch({ type: "create_item", payload: response.data });

    navigate("Home");
  } catch (err) {
    console.log(err);
  }
};

export const { Provider, Context } = createDataContext(
  itemReducer,
  { createItem, fetchItems },
  []
);

这是AuthContext,用于登录和注册功能,并使用AsyncStorage。让我知道你们是否需要查看Auth的节点功能。

import createDataContext from "./createDataContext";
import sellerApi from "../api/seller";
import { navigate } from "../navigationRef";

const authReducer = (state, action) => {
  switch (action.type) {
    case "add_error":
      return { ...state, errorMessage: action.payload };
    case "signup":
      return { errorMessage: "", token: action.payload };
    case "signin":
      return { errorMessage: "", token: action.payload };
    case "fetch_user":
      return action.payload;
    case "clear_error_message":
      return { ...state, errorMessage: "" };
    case "signout":
      return { token: null, errorMessage: "" };
    default:
      return state;
  }
};

const tryLocalSignin = dispatch => async () => {
  const token = await AsyncStorage.getItem("token");
  if (token) {
    dispatch({ type: "signin", payload: token });
    navigate("Home");
  } else {
    navigate("loginFlow");
  }
};

const clearErrorMessage = dispatch => {
  dispatch({ type: "clear_error_message" });
};

const signup = dispatch => async ({ name, phone, email, password }) => {
  try {
    const response = await sellerApi.post("/api/users", {
      name,
      phone,
      email,
      password
    });
    //this is the other place the error might be happening i need this to save in the phone local storage
    await AsyncStorage.setItem("token", response.data);
    console.log(response.data);
    dispatch({ type: "signup", payload: response.data.token });

    navigate("Home");
  } catch (err) {
    dispatch({ type: "add_error", payload: "FAIL" });
  }
};

const signin = dispatch => async ({ email, password }) => {
  try {
    const response = await sellerApi.post("/api/auth", {
      email,
      password
    });
    await AsyncStorage.setItem("token", response.data);
    console.log(response.data);
    dispatch({ type: "signin", payload: response.data.token });

    navigate("Home");
  } catch (err) {
    dispatch({ type: "add_error", payload: "FAIL" });
  } 
}; 

// const fetchUser = dispatch => async () => {
//   const response = await sellerApi.get("/auth");
//   dispatch({ type: "fetch_user", payload: response.data });
// };

//need to get the users info to display it in the accountScreen

const signout = dispatch => async () => {
  await AsyncStorage.removeItem("token");
  dispatch({ type: "signout" });
  navigate("loginFlow");
};

export const { Provider, Context } = createDataContext(
  authReducer,
  { signup, signin, signout, tryLocalSignin },
  { token: null, errorMessage: "" }
);

这是Auth函数的后端,可确保用户在开始发送帖子请求之前已登录----

const jwt = require("jsonwebtoken");
const config = require("config");


module.exports = function (req, res, next) {
  const token = req.header("x-auth-token");
  if (!token) return res.status(401).send("Access denied");

  try {
    const decoded = jwt.verify(token, config.get("jwtPrivateKey"));
    req.user = decoded;
    next();
  } catch (ex) {
    res.status(400).send("Invalid token.");
  }
}

这是您注册和登录时的发帖请求非常相似的地方-

router.post("/", async (req, res) => {
  const { error } = validate(req.body);
  if (error) return res.status(400).send(error.details[0].message);

  let user = await User.findOne({ email: req.body.email });
  if (user) return res.status(400).send("User already registered.");

  user = new User(_.pick(req.body, "name", "phone", "email", "password"));
  const salt = await bcrypt.genSalt(10);
  user.password = await bcrypt.hash(user.password, salt);

  await user.save();

  const token = user.generateAuthToken();
  res.header("x-auth-token", token).send(token);
});

请帮助

1 个答案:

答案 0 :(得分:0)

像这样的import {AsyncStorage} from 'react-native';那样导入异步存储已被弃用。您可以在这里async storage进行检查。

这就是为什么我认为AsyncStorage无法正常工作的原因,请尝试下载此rn-community-async-storage。首先打包,然后像

一样导入AsyncStorage
import AsyncStorage from '@react-native-community/async-storage';

希望有帮助。毫无疑问