【问题标题】:Axios VS Postman request get different responsesAxios VS Postman 请求得到不同的响应
【发布时间】:2020-09-01 19:51:56
【问题描述】:

大家好,我在连接 API 时遇到了一个奇怪的问题。

当我使用 Postman 时,一切都很顺利,但如果我使用 Axios 发出请求,则响应会有所不同。举个例子,我想找一个 id 为 616 的客户;

客户

await axios
        .post("/api/getClient", {
          id: 616,
        }).then(data => console.log(data))

后台

// GET CLIENT
app.post('/api/getClient', async (req, res) => {
  const d = await axios.get(`${baseURL}/client/account/:client_id`, {
    headers: headers,
    data: {
      id: req.body.id
    }
  })
  res.send(d.data)
  res.end()
});

来自 axios 的响应如下所示

data: {
  error: false,
  user: {
    profile: null,
    user_addresses: [],
    safe_credits: 0,
    rating: 5
  }
}

来自邮递员

{
    "error": false,
    "user": {
        "profile": {
            "id": 616,
            "phone_number": "07744444444",
            "country_code": "44",
            "email": "email@example.com",
            "first_name": "John",
            "last_name": "Doe",
            "password": null,
            "os": "iOS",
            "token": "0c9c09e7dc2f009b4cfdb2e4666ead9e",
            "version": "",
            "photo": "",
            "gender": "male",
            "registered_date": "2020-05-08T14:55:05.000Z",
            "enabled": 1,
            "socketId": "",
            "stripe_id": "cus_HF1eUUdada54JKN"
        },
        "user_addresses": [],
        "safe_credits": 0,
        "rating": 5
    }
}

【问题讨论】:

  • 我们将不得不查看您的邮递员收藏以帮助您
  • 请将邮递员请求导出为 curl
  • 检查您传递给邮递员请求的标头。您可能在 axios 请求中遗漏了一些内容
  • @DeepakTerse 我有 JSON 格式
  • @MarkusHayner 与我们分享

标签: javascript axios postman


【解决方案1】:

您应该能够将 ID 附加到您的 API URL,而不是在您的请求中使用 data

 const d = await axios.get(`${baseURL}/client/account/${req.body.id}`, {
   ...
 });

【讨论】:

  • API 使用路径来定义请求的类型(客户端、帐户)和参数(帐户 ID)。我们只是将帐户 ID 粘贴到 API 期望的 URL 上。
  • 好的,我想如何使用不使用路径中的变量的路径,例如 localhost:3000/ 将接收电话、电子邮件、名字、姓氏、密码来注册新用户。如果不在数据中,我该如何处理?
  • 您很可能会使用 Axios 发出 POST 请求(而不是 GET)。在这种情况下,您发布的信息应包含在数据中。
【解决方案2】:

我最近遇到了类似的问题。

在邮递员中确保删除所有 cookie,因为这可能会影响结果。

Postman 在同一域上的不同请求之间存储 cookie。而 axios(或任何其他后端库)可能不会。

在邮递员的“发送”按钮下,检查 cookie,删除您在那里找到的所有 cookie,然后重新执行。这可能会给您在 axios 中相同的结果。

【讨论】:

    猜你喜欢
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 2020-10-23
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多