I have attached my javascript code. Please help someone where the mistake is in my code.
document.addEventListener('DOMContentLoaded', function () { let requestBodyEl = document.getElementById('requestBody'); let sendPostRequestBtn = document.getElementById('sendPostRequestBtn'); let requestStatus = document.getElementById('requestStatus'); let httpResponse = document.getElementById('httpResponse');
function buttonClick() { let userInput = requestBodyEl.value; let options = { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', Authorization: 'Bearer ACCESS-TOKEN', }, body: JSON.stringify(userInput), };
fetch('https://gorest.co.in/public-api/users', options)
.then(function (response) {
return response.json();
})
.then(function (jsonData) {
requestStatus.textContent = jsonData.code;
console.log(jsonData);
httpResponse.textContent = JSON.stringify(jsonData);
});
}
sendPostRequestBtn.addEventListener('click', buttonClick); });
Ignore the ACCESS-TOKEN, as I have used the access token.
When I try to POST this data. { "name": "Vinod", "email": "[email protected]", "gender": "Male", "status": "Active" }
I am getting this as response. {"code":422,"meta":null,"data":[{"field":"email","message":"can't be blank"},{"field":"name","message":"can't be blank"},{"field":"gender","message":"can't be blank, can be male of female"},{"field":"status","message":"can't be blank"}]}
you are sending data as raw test instead of json string
"{\n\"name\": \"Rakshita\",\n\"email\": \"[email protected]\",\n\"gender\": \"Female\",\n\"status\": \"Active\"\n}"
May be just this will work httpResponse.textContent = jsonData;
Below is the code used in the "Rest Console" of this application
```
$(document).on('click', '#rsq_send', () => {
let rsq = {};
rsq.url = $('#rsq_url').val();
rsq.type = $('#rsq_type').val();
rsq.headers = {};
$("#rsq_form").find("input[name='rsq_header_name[]']").each((i, e) => {
if ($(e).val()) {
rsq.headers[$(e).val()] = $("#rsq_form").find("input[name='rsq_header_value[]']").eq(i).val();
}
});
rsq.headers['Accept'] = 'application/json, text/plain, */*';
rsq.data = $('#rsq_body').val();
rsq.contentType = 'application/json';
rsq.beforeSend = () => {
$('#rsp_headers').html('');
$('#rsp_body').html('');
$('#rsp-body-title').html('');
};
var jqXHR = $.ajax(rsq);
jqXHR.done((data, textStatus, jqXHR) => {
$('#rsp_body').html(JSON.stringify(data, null, 2));
$('#rsp_headers').html(jqXHR.getAllResponseHeaders());
$('#rsp-body-title').html('Status: ' + jqXHR.status);
});
jqXHR.fail(function (jqXHR, textStatus, errorThrown) {
$('#rsp_body').html(JSON.stringify(jqXHR.responseJSON, null, 2));
$('#rsp_headers').html(jqXHR.getAllResponseHeaders());
$('#rsp-body-title').html('Status: ' + jqXHR.status);
});
}); ```