Reputation: 6240
var express = require('express');
var router = express.Router();
router.post("/", function(req, res, next) {
console.log('Yes1');
if(!req.body.username || !req.body.password){
console.log('Yes2');
return res.status(401).json(JSON.stringify({
error: 'Username or Password are not set'
}));
}else{
console.log('Yes3');
return res.status(200).json(JSON.stringify({
data: 'Okay'
}));
}
//error handler
router.use(function(err, req, res, next) {
res.status(500).json(JSON.stringify({
error: err
}));
});
module.exports = router;
From the front end I am sending a username and password. I am expecting to either be receiving errors 200 or 401. For some reason though I receiving error 500 which is the default error handler. I am not sure how it is coming here. On my server console Yes1 and Yes2 are being printed so why am I not getting error 401?
Upvotes: 0
Views: 2448
Reputation: 1460
I don't know if you have more code or not, but you need to install your router with app.use('/', router)
.
You also need to install the body-parser
middleware to be able to parse req.body
.
Your whole application should look something like this:
// router.js
var express = require('express');
var router = express.Router();
router.post("/", function(req, res, next) {
console.log('Yes1');
console.log(req.body);
if(!req.body.username || !req.body.password){
console.log('Yes2');
return res.status(401).json(JSON.stringify({
error: 'Username or Password are not set'
}));
}else{
console.log('Yes3');
return res.status(200).json(JSON.stringify({
data: 'Okay'
}));
}
});
//error handler
router.use(function(err, req, res, next) {
res.status(500).json(JSON.stringify({
error: err
}));
});
module.exports = router;
// server.js
var express = require('express');
var bodyParser = require('body-parser');
var customRouter = require('./router.js');
var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use('/', customRouter);
app.listen(3000, function () {
console.log('Listening on port 3000...');
});
See error handling and routing documentation.
Upvotes: 2
Reputation: 344
It appears that your middleware handler is firing, because 401 is an error, and you are resetting the status to 500.
Upvotes: 0