jayzee
jayzee

Reputation: 225

react js Axios 401 Unauthorized although i have my Bearer String correct

I have a deleteUser API that deletes a user from my MySql Database. my API is working perfectly on postman. nut when i call my api from my react app it returns an error

Failed to load resource: the server responded with a status of 401 (Unauthorized)

---this is my delete request---

const handleRowDelete = (oldData, resolve) => {
    axios
      .post("/deleteUser/" + oldData.userId, {
        headers: {
          Authorization: "Bearer " + sessionStorage.getItem("token"),
        },
      })
      .then((res) => {
        window.location.reload(false);
      })
      .catch((error) => {
        setErrorMessages(["Update failed! Server error"]);
        setIserror(true);
        resolve();
      });
  };

and even more i have un updateUser API that im also calling in the same component and it working perfectly

---this is the update api---

axios
        .post("/updateUser/" + newData.userId, newData, {
          headers: {
            Authorization: "Bearer " + sessionStorage.getItem("token"),
          },
        })
        .then((res) => {
          window.location.reload(false);
        })
        .catch((error) => {
          setErrorMessages(["Update failed! Server error"]);
          setIserror(true);
          resolve();
        });
    } else {
      setErrorMessages(errorList);
      setIserror(true);
      resolve();
    }

its exactly the same but the delete api is not working i cant figure out why.(401 unauthorized)

Upvotes: 0

Views: 1006

Answers (1)

Danila
Danila

Reputation: 18476

You pass your headers as the second argument to axios.post, but actually it should be third argument. Second argument is data.

    axios.post(
        "/deleteUser/" + oldData.userId,
        {}, // add empty object or null here as second argument
        {
          headers: {
            Authorization: "Bearer " + sessionStorage.getItem("token"),
        },
      })

Also, if you can modify your API then it would be better to use DELETE method for user deletion, not POST. (and then your code would work because axios.delete accepts headers as second argument)

Upvotes: 2

Related Questions