【问题标题】:axios get request with body and headeraxios 获取带有正文和标头的请求
【发布时间】:2022-01-23 10:55:26
【问题描述】:

我怎么能这样,将带有授权令牌的正文参数和标头发送到此

const searchByDate = async ({ date1, date2 }) => {
  const tokenApp = window.localStorage.getItem('token');
  const { data: res } = await axios.get(`${baseUrl}/search`, {
    data: { date1: date1, date2: date2 },
    headers: { Authorization: `${tokenApp}` },
  });
  return res;
};

到目前为止,它给我一个错误缺少必需的请求正文

【问题讨论】:

标签: javascript api axios get


【解决方案1】:

一般来说,body 对于 GET 请求没有意义,因此 axios 不支持它。

如果你阅读axios config documentation,你会发现

//data是要作为请求体发送的数据
// 仅适用于请求方法 'PUT'、'POST'、'DELETE 和 'PATCH'

您可以在HTTP GET with request body 了解更多信息。


如果您想在 GET 请求中发送数据,请使用 params 属性

//params是要随请求一起发送的URL参数
// 必须是普通对象或 URLSearchParams 对象

【讨论】:

    【解决方案2】:

    尝试使用params 属性发送数据:

    const { data: res } = await axios.get(`${baseUrl}/search`, {
        params: { date1, date2 },
        headers: { Authorization: `${tokenApp}` },
      });
    

    【讨论】:

      猜你喜欢
      • 2018-12-06
      • 2021-08-13
      • 2020-12-23
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-01
      相关资源
      最近更新 更多