0

I'm just creating a website using React and used axios for fetch some apis, already set the header config but still got 401 error.

Neither using

  useEffect(() => {
    const user = getUser();
    const token = getToken();
    if (user !== null) {
      axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
      axios
        .post(Api.getMyMatter, { user_id: user.user_id })
        .then((res) => {
          const data = res.data;
          setData(data);
          console.log(data);
          setIsReady(true);
        })
        .catch((err) => {
          console.log(err);
        });
    }
  }, []);

nor

  useEffect(() => {
    const user = getUser();
    const token = getToken();
    if (user !== null) {
      axios
        .post(
          Api.getMyMatter,
          { user_id: user.user_id },
          { headers: { Authorization: `Bearer ${token}` } }
        )
        .then((res) => {
          const data = res.data;
          setData(data);
          console.log(data);
          setIsReady(true);
        })
        .catch((err) => {
          console.log(err);
        });
    }
  }, []);

it still give me an 401 error like this. request error

Anyone know why? Thanks.

Devanada
  • 147
  • 9
  • 1
    I think moesif cors (browser plugin) can solve your problem. I have the same issue when I was creating a react app and calling a free api. – carlo Jul 12 '21 at 09:20
  • You're getting an error in response to the preflight request the browser is using to ask permission to make a POST request with credentials. – Quentin Jul 12 '21 at 09:21
  • 1
    Feels like a CORS issue. Is your domain whitelisted for access control origin headers ? – Pranay Tripathi Jul 12 '21 at 09:21
  • I dunno, but it's my colleague's domain that used as an api, but it's no problem when using postman to test it – Devanada Jul 12 '21 at 09:26
  • @Devanada — Postman, as the duplicate question explains, does not enforce the Same Origin Policy. – Quentin Jul 12 '21 at 09:27

0 Answers0