Ahmed Hassan
Ahmed Hassan

Reputation: 1

Token undefined in put and patch request. MERN stack application

Working with a mern application. I am passing token in authorization header. The issue is whenever I use put or patch method from frontend, token is undefined. Get, Post, Delete requests are working fine. Api is working fine with postman too.

frontend action ->

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

Backend middleware function ->

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

Upvotes: 0

Views: 150

Answers (1)

Sajeersayed Ali
Sajeersayed Ali

Reputation: 1

while doing PUT request pass parameters like id in req.body

rather in req.params or req.query

Upvotes: 0

Related Questions