axios 在put和patch请求中未定义令牌,MERN堆栈应用程序

bihw5rsg  于 12个月前  发布在  iOS
关注(0)|答案(1)|浏览(141)

使用一个mern应用程序。我在授权头中传递token。问题是每当我从前端使用put或patch方法时,token都是未定义的。Get,Post,Delete请求工作正常。API也可以与postman一起工作。
前端操作->

export const approveClient = (id) => async (dispatch) => {
  try {
    const config = {
      headers: {
        Authorization: `${localStorage.getItem("token")}`,
        },
    };
    dispatch({ type: adminConstants.APPROVECLIENT_REQUEST });
    const res = await axios.put(`/admin/approveClient/${id}`, config);
    dispatch({
      type: adminConstants.APPROVECLIENT_SUCCESS,
      payload: res.data,
    });
  } catch (error) {
    dispatch({
      type: adminConstants.APPROVECLIENT_FAIL,
      payload: error.response.data,
    });
  }
};

字符串
后端中间件功能->

const isAuthenticated = async (req, res, next) => {
  try {
    const token = req.headers.authorization;
    if (!token) {
      return res.status(401).json({ success: false, message: "Not logged in" });
    }
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const user = await User.findById(decoded._id);
    const client = await Client.findById(decoded._id);
    const admin = await Admin.findById(decoded._id);
    if (user) {
      req.user = user;
    }
    if (client) {
      req.user = client;
    }
    if (admin) {
      req.user = admin;
    }

    next();
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
};

cnjp1d6j

cnjp1d6j1#

在执行PUT请求时,在req.body中传递像id这样的参数
而是在req.params或req.query中

相关问题