为何向ReqRes发送POST请求后,响应未返回提交的参数?
问题:POST请求到ReqRes.in后响应未返回发送的数据?
我正在学习API相关知识,尝试向ReqRes.in发送一个简单的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、参数获取方式、表单提交方法、变量和函数名、移除函数中的条件判断等,但都没有解决问题。请问我哪里出错了?
解决方法
问题核心是未设置Content-Type: application/json请求头。当你通过JSON.stringify()将数据转为JSON字符串发送时,必须明确告知服务器请求体的格式是JSON,否则ReqRes.in的服务器无法正确解析你提交的内容,也就不会在响应中返回这些数据。
修改后的代码
只需在xhttp.open()之后、xhttp.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); // 新增:设置请求头,告诉服务器发送的是JSON数据 xhttp.setRequestHeader("Content-Type", "application/json"); xhttp.send(JSON.stringify(newUser)); };
添加这行代码后,服务器就能正确解析你提交的JSON数据,响应里会包含你传入的name和email字段,和预期一致。
内容的提问来源于stack exchange,提问作者Mateus Oliveira
相关产品推荐
相关产品推荐

