I'm learning about API etc., and I was trying to do a simple POST request to ReqRes.in
. Although the POST response suggests that the request was successful, it doesn't include the data I'm sending, which is not the behavior expected according to the documentation...
My code:
<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>
On submitting, I was expecting this response:
Object { name: "User Input Value", email: "Email Input Value", id: "848", createdAt: "2024-05-09T01:17:49.098Z" }
But what I receive is:
Object { id: "848", createdAt: "2024-05-09T01:17:49.098Z" }
I tested several combinations of ID, values capturing, methods of form submit, variables and function names, removal of If's in the function etc., nothing worked. What am I doing wrong?
Looks like the only thing you are missing is to set the "Content-type" header to json. Do this by adding the line:
xhttp.setRequestHeader("Content-type","application/json")
between the .open() and .send() calls.
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>