Node.js
Vilsam API-design: bästa metoder
Sök…
Felhantering: FÅ alla resurser
Hur hanterar du fel istället för att logga in dem på konsolen?
Dålig väg:
Router.route('/')
.get((req, res) => {
Request.find((err, r) => {
if(err){
console.log(err)
} else {
res.json(r)
}
})
})
.post((req, res) => {
const request = new Request({
type: req.body.type,
info: req.body.info
});
request.info.user = req.user._id;
console.log("ABOUT TO SAVE REQUEST", request);
request.save((err, r) => {
if (err) {
res.json({ message: 'there was an error saving your r' });
} else {
res.json(r);
}
});
});
Bättre sätt:
Router.route('/')
.get((req, res) => {
Request.find((err, r) => {
if(err){
console.log(err)
} else {
return next(err)
}
})
})
.post((req, res) => {
const request = new Request({
type: req.body.type,
info: req.body.info
});
request.info.user = req.user._id;
console.log("ABOUT TO SAVE REQUEST", request);
request.save((err, r) => {
if (err) {
return next(err)
} else {
res.json(r);
}
});
});
Modified text is an extract of the original Stack Overflow Documentation
Licensierat under CC BY-SA 3.0
Inte anslutet till Stack Overflow