繁体   English   中英

尝试使用 fetch 而不是 axios 发出 POST 请求,但 fetch 请求的响应返回错误,而 axios 没有

[英]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

我有一个 function ,它使用 Axios 发送一个成功通过的 POST 请求,我得到了正确的响应。 现在我想尝试使用 fetch 来执行完全相同的 POST 请求。 不幸的是,获取请求返回415 Unsupported Media Type响应错误,我不知道为什么。

目前:

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

我用来替换 Axios POST 请求的获取代码。

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

fetch不将普通对象识别为主体。

如果要发送 JSON 则需要对数据进行编码并自己设置内容类型 header。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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