skip to Main Content

I want to send a patch request without a body, so in Postman, I only require to send the request without body, but in the frontend, I need the second argument if not I will get a 401 error.

I’ve tried an empty string, NULL, and empty object – but it’s still not working. It didn’t return the same output as in Postman:

export const somethingNeedsPatching = async (details) => {
  const { token } = JSON.parse(localStorage.getItem("userData"));
  const url = `${
    import.meta.env.VITE_APP_SNATCH_URL
  }/something/somethingPath/${details.something}
  `;

  try {
    const res = await axios.patch(
      url,
      {},
      {
        headers: {
          "Content-Type": "application/json",
          "Content-Length": 0,
          Authorization: `Bearer ${token}`,
        },
      }
    );
    return res;
  } catch (error) {
    console.log(error);

    return error.response;
  }
};

In Postman, the request is sent without a body and it works, but in the frontend, Axios requires a second parameter. If I left the url with the header, I’ll automatically get a 401 error.

enter image description here

2

Answers


  1. I think may be due to the url also you may get the error so you may try as:

    const url = `${
    process.env.VITE_APP_SNATCH_URL
    

    }/something/somethingPath/${details.something}
    `;

    and in header too you have to remove the content-length line and should try this as:

         headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
    

    May be this will help you.

    Login or Signup to reply.
  2. The main issue I see is that your URL has a trailing newline. Also, the URL in the screenshot has a trailing /.

    You also have redundant headers content-type and content-length.

    In order to set no request body, you should be able to pass null or undefined. Alternately, use the general axios() method without setting a data property.

    Separating baseURL and url can also make your code cleaner

    const res = await axios.patch(
      `/something/somethingPath/${details.something}/`, // no newline, end in "/"
      null,
      {
        baseURL: import.meta.env.VITE_APP_SNATCH_URL,
        headers: {
          authorization: `Bearer ${token}`,
        },
      }
    );
    
    // or
    
    const res = await axios({
      method: "patch",
      url: `/something/somethingPath/${details.something}/`, // no newline, end in "/"
      baseURL: import.meta.env.VITE_APP_SNATCH_URL,
      headers: {
        authorization: `Bearer ${token}`,
      },
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search