为什么 ReqRes 对我的 POST 请求的响应没有返回我包含的值?

问题描述 投票:0回答:1

我正在学习 API 等,我试图向 ReqRes.in 发送一个简单的 POST 请求。虽然 POST 响应表明请求成功,但它不包含我正在发送的数据,这不是文档预期的行为...

我的代码:

<script>
function startAPI() {
  let xhttp;
  xhttp = new XMLHttpRequest;
  xhttp.onreadystatechange = () => {
    if (xhttp.readyState == 4) {
      if (xhttp.status == 201) {
        let reqresponse = JSON.parse(xhttp.responseText);
        console.log(reqresponse)
      };
    };
  };
  let newUser = {
    name: document.querySelector("#userName").value,
    email: document.querySelector("#userEmail").value,
  };
  xhttp.open('POST', 'https://reqres.in/api/users', true);
  xhttp.send(JSON.stringify(newUser));
};
</script>
<body>
<form onsubmit="startAPI(); return false">
  <p>
    <label for="userName">Nome: </label>
    <input type="text" name="userName" id="userName">
  </p>
  <p>
    <label for="userEmail">Email: </label>
    <input type="email" name="userEmail" id="userEmail">
  </p>
  <p>
    <input type="submit" value="Create User">
  </p>
</form>
</body>

提交时,我期待这样的回复:

Object { name: "User Input Value", email: "Email Input Value", id: "848", createdAt: "2024-05-09T01:17:49.098Z" }

但是我收到的是:

Object { id: "848", createdAt: "2024-05-09T01:17:49.098Z" }

我测试了 ID、值捕获、表单提交方法、变量和函数名称、函数中 If 的删除等多种组合,但没有任何效果。 我做错了什么?

谢谢大家,平安。

javascript json api post xmlhttprequest
1个回答
0
投票

看起来您唯一缺少的就是将“Content-type”标头设置为 json。通过添加以下行来完成此操作:

xhttp.setRequestHeader("内容类型","application/json")

在 .open() 和 .send() 调用之间。

function startAPI( ) {
  let xhttp;
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = () => {
    if (xhttp.readyState == 4) {
      if (xhttp.status == 201) {
        let reqresponse = JSON.parse(xhttp.responseText);
        console.log(reqresponse);
      }
    }
  }
  let newUser = {
    name: document.querySelector("#userName").value,
    email: document.querySelector("#userEmail").value,
  };
  xhttp.open('POST', 'https://reqres.in/api/users', true);
  xhttp.setRequestHeader("Content-type","application/json");
  xhttp.send(JSON.stringify(newUser));
}
        <form onsubmit="startAPI(); return false">
          <p>
            <label for="userName">Nome: </label>
            <input type="text" name="userName" id="userName">
          </p>
          <p>
            <label for="userEmail">Email: </label>
            <input type="email" name="userEmail" id="userEmail">
          </p>
          <p>
            <input type="submit" value="Create User">
          </p>
        </form>

© www.soinside.com 2019 - 2024. All rights reserved.