【问题标题】:Getting a 422 Error on Post request, but I think my request is being sent correclty在发布请求时收到 422 错误,但我认为我的请求正在正确发送
【发布时间】:2020-04-28 20:59:16
【问题描述】:

我必须向提供给我的 API 发出 POST 请求。

我应该向它发送一些数据并取回JWT 令牌。

我必须发送的数据是一个名为 data 的对象,如下所示:

{
    "firstName": "Jane",
    "address": "Lohmühlenstraße 65",
    "numberOfChildren": 2,
    "occupation": "EMPLOYED",
    "email": "jane.doe@getpopsure.com"
}

API 文档如下所示:

curl https://challenge-dot-popsure-204813.appspot.com/user \
-H 'Content-Type: application/json' \
-d '{"firstName":"Jane","address":"Lohmühlenstraße 65","numberOfChildren":2,"occupation":"EMPLOYED","email":"jane.doe@getpopsure.com"}' \
-X POST

我正在使用 axios 发送带有对象的 POST 请求,但我收到 422 错误:

Failed to load resource: the server responded with a status of 422 ()

这是我的 POST 请求,其中data 是上面的对象:

    axios.post('https://challenge-dot-popsure-204813.appspot.com/user', data)
    .then(function (response) {
      debugger
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });

任何想法可能是什么问题?

【问题讨论】:

  • 你看到 error arg 在 catch 块中有什么了吗?
  • 问题可能是地址Lohmühlenstraße中的特殊字符,您是否确认请求在Postman或类似工具中正确发送?
  • @segFault 我刚刚尝试在 Postman 中执行此发布请求 - 它对我有用
  • 邮递员也为我工作,我无法在this plunker 中重现该问题。也许查看整个错误响应会有所帮助。

标签: javascript post http-status-code-422


【解决方案1】:

我能够通过删除或使 JSON 数据无效来重现 422 错误。例如删除/重命名“firstName”属性。

例子:

{
    "name": "Jane",
    "address": "Lohmühlenstraße 65",
    "numberOfChildren": 2,
    "occupation": "EMPLOYED",
    "email": "jane.doe@getpopsure.com"
}

导致:422 无法处理的实体

{
    "errors": {
        "firstName": [
            "Missing data for required field."
        ],
        "name": [
            "Unknown field."
        ]
    }
}

Plunker

我认为您面临的问题是,当您制作 axios.post 时,您所期望的数据并不全部存在,从而导致您看到的错误。确保请求中发送的数据事先包含所有有效的字段和值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    相关资源
    最近更新 更多