express
express copied to clipboard
Why I can't send an error to front end through res.json()?
I need to send an error object to front. just like
return res.json({ err: new Error('error') })
// also try res.send(JSON.stringify(new Error('error')))
but in browser
console.log(theErrorFromBackend) // {} ,get an empty object
node version 6.10.3 npm version 3.10.10 os macOS 10.12.4 express version ~4.15.2
to reproduce
$ express demo
$ cd demo && npm install # or yarn
and then modify demo/routes/users.js
router.get('/', function(req, res, next) {
res.send(JSON.stringify(new Error('1231232')));
});
run npm start and visit localhost/3000/users in browser
Sorry I post this issue, Finally I realize it is a feature not an issue😅 , I should handle the err in middleware, should call next(err) inside the api method.
The explanation here might be helpful: https://stackoverflow.com/questions/44152189/error-in-promise-not-sending-any-error-in-response-object-in-nodejs-express-mong