簡體   English   中英

如何處理nodejs表示的響應和下一步

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM