[英]how to handle response and next in nodejs express
我想知道我应该如何处理响应和接下来的快递。
我的理解是,当我说res.send(...) - >返回一个响应
如果我想抛出错误,我说下一个(新错误('不管')) - >使用快速错误处理程序自动设置http状态代码。
我可以做其中任何一个但不是,但看起来我搞砸了。
谁能举个例子?
我试过了,
somefunc(err, req, res, next) {
if(err) {
res.send(500, 'some error');
return next(err);
}
}
return [somefunc, express.errorHandler()];
谢谢。
您可以注册一些中间件来处理错误:
app.use(function(err, req, res, next){
console.error(err.stack);
res.send(500, 'Something broke!');
});
如果在逻辑中遇到错误,您也可以简单地发送500响应
function loginUser(req, res, next) {
try {
var valid;
//code to check user
if (valid) {
next();
} else {
res.send(401, 'not authorized');
}
} catch (err) {
res.send(500, 'Oopsy');
}
}
app.get('/some/route',loginUser, function(req, res) {
// ...
});
只需跳过return next();
部分。 使用return res.send(500,'some error');
调用next
会导致调用next
一个中间件,在这种情况下,IMO不是您想要的。 我在这里写了更多关于它的内容
这是快速堆栈的最小示例:
express = require('express');
app = express();
app.configure(function() {
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(app.router());
app.use(express.static(__dirname + '/public'));
});
app.get('/', function(req, res) {
if (some error)
res.send(500, 'Some error');
else
res.send('<body>Hello</body>');
});
app.listen(3000); // listen on port 3000
get请求将由router
中间件调用。 中间件被解析为链。 您可以在此链中使用自定义中间件,例如:
app.configure(function() {
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(function(req, res, next){
if (some condition)
res.send(500, 'No way'); // this will break the request chain
else
next(); // this will continue processing and will call app.router middleware
});
app.use(app.router());
app.use(express.static(__dirname + '/public'));
});
app.router
中间件负责根据请求的URL调用适当的方法(如app.get('/')
)。 如果找不到,则调用next()
将控制权传递给express.static
中间件,该中间件试图在/public/
文件夹中查找静态文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.