简体   繁体   中英

Trying to use fetch instead of axios to make a POST request, but the response from the fetch request returns an error, whereas axios doesn't

I have a function which uses Axios to send a POST request which goes through successfully and I get the right response. Now I want to try using fetch to do the exact same POST request. Unfortunately, the fetch request returns a 415 Unsupported Media Type response error and I have no idea why.

Currently:

  onBeforeUnload = () => {
    try {
      const defaultPresence = {
        presence: 'AVAILABLE',
        message: '',
      };
      const url = getServerURL() + urls.PRESENCE;

      axios.post(
        url,
        defaultPresence,
        {
          headers: {
            Authorization: `Bearer ${getAccessToken()}`,
          },
        },
      );
    } catch (error) {
      console.log(error);
    }
  }

The fetch code I've used to replace the Axios POST request.

  fetch(url, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${getAccessToken()}`,
    },
    body: defaultPresence,
  });

fetch does not recognise plain objects as the body.

If you want to send JSON then you need to encode the data and set the content-type header yourself.

  fetch(url, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${getAccessToken()}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(defaultPresence),
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM