【问题标题】:How to send body data with headers with axios get request如何使用axios get请求发送带有标题的正文数据
【发布时间】:2021-08-31 22:19:19
【问题描述】:

我正在尝试从具有所有者 = 值和日期 = 值的 api 获取请求。使用 Postman,我可以发送带有正文 json 的请求以获取结果。但是,当使用 Axios 时,我无法得到结果。如何将正文 json 发送到标题并返回结果。使用 Axios 我得到一个空的响应

没用

var searchRecord = {
        owner: 'wxTWH8zqSwaIXPAVsjZoRCkvjx73',
        date: '2021-09-02',
      };

      var config = {
        method: 'get',
        url: 'http://localhost:3000/records/owner',
        headers: {
          'Content-Type': 'application/json',
        },
        body: searchRecord,
      };
      axios
        .get('http://localhost:3000/records/owner', config)
        .then(function (response) {
          // handle success
          console.log(JSON.stringify(response.data));
        })
        .catch(function (error) {
          console.log(error);
        })

在 Postman 中,我可以在正文中发送以下内容并获得我需要的结果

{
  owner: 'wxTWH8zqSwaIXPAVsjZoRCkvjx73',
  date: '2021-09-02',
}

输出响应将是:

{
        "instantMessage": "false",
        "isComplete": false,
        "_id": "612e5cede496ce8f1b6a244c",
        "date": "2021-08-31",
        "title": "Ming first",
        "description": "Test",
        "remindTime": "1630432800",
        "owner": "wxTWH8zqSwaIXPAVsjZoRCkvjx73",
    }

【问题讨论】:

  • 您使用的是get,请改用post,当指定method 时,您通常会改用axios.request(config)
  • 我按照您的说明更新了代码,但是现在我收到错误请求失败,状态码为 403
  • { owner: 'wxTWH8zqSwaIXPAVsjZoRCkvjx73', date: '2021-09-02', } 你把这个放在邮递员哪里?在 RAW 或使用 url 编码?
  • 我把它放在原始身体部分

标签: reactjs react-native axios postman


【解决方案1】:

我想我也有同样的问题。 当我使用邮递员测试我的后端时 - 一切正常。

所以目的是从端点获取数据(作为正文,我想提供用户电子邮件):

data = {
  "user_email": test@test.com
}

.get("api/test_endpoint/", config, data)

How to send body data and headers with axios get request?

上面的最后一条评论选择“2014 年之后的标准允许 GET Body”。

那么最后是可能的还是正确的做法?

编辑:

我当然要补充:

可以将所需数据作为获取请求 url 的一部分添加(但不能登录或通过!!!) 因此,例如登录的管理员用户有可能通过电子邮件为某些用户获取数据,例如:

get('localhost/api/test_endpoint?user_email=test@test.com')

那么为什么不使用正文作为获取请求的一部分呢?

【讨论】:

    猜你喜欢
    • 2020-08-16
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 2019-10-21
    • 2022-01-16
    • 1970-01-01
    • 2017-08-31
    相关资源
    最近更新 更多