How to get message body for 4xx response? Or is it expected behaviour?
See original GitHub issueServer is set up to return 200 and json object when server side validation and all further server work passes. It returns 400 on server side validation error It returns 500 on server side logic/DB/whatever error
Returning 400 is good praxis for server side validation failure (http://stackoverflow.com/a/34324179, http://stackoverflow.com/a/3290198, a.o.) Of course in real world there is also client side validation which forbids sending invalid form
Example for 400
Client
import request from 'superagent';
...
let sendToServerData;
// sendToServerData = {one: 'isOne', two: 'isTwo'}; // test with data
sendToServerData = {}; // test with no data
request
.post('/')
.send(sendToServerData)
.set('Accept', 'application/json')
.then((sucess) => {
console.log('we have sucsess', sucess);
}, (faulure) => {
console.log('we have failure', faulure);
});
Server
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// get input
$rest_json = file_get_contents("php://input");
// decode and put in post
$_POST = json_decode($rest_json, true);
// set header
header_remove();
header('Content-type:application/json;charset=utf-8');
// if empty return 400 and json explaining things
if(empty($_POST)) {
http_response_code(400);
header('Status: 400');
exit(json_encode(array(
'status' => 400,
'message' => 'no empty posts my friend'
)));
}
// just return back 200 and json explaining things
http_response_code(200);
header('Status: 200');
exit(json_encode(array(
'status' => 200,
'message' => 'all fine!'
)));
}
when sendToServerData
is populated, all fine as expected - sucess
contains all the payload. when sendToServerData
is empty console prints we have failure Error: Bad Request(…)
thus faulure
object does not contain any server payload, it does not even contain status code.
Is it expected (like “superagent way” would be returning 200 also on server side validation error, just set the payload to contain that there is actually server side validation error)? Or am I missing something? is it possibe to get object (failure
) that contains server code and message on non 2xx status?
superagent@2.2.0
Thanks!
Issue Analytics
- State:
- Created 7 years ago
- Comments:20 (11 by maintainers)
Top GitHub Comments
should work
Use
request.post('/').send(sendToServerData).type('json').then(handleSuccess).catch((error) => {console.log(error.response.body)})