繁体   English   中英

如何处理restify中的403 HTTP错误?

[英]How to handle 403 HTTP error in restify?

我一直在尝试处理 restify 中的 HTTP 错误。 这些是我到目前为止一直在尝试的代码:

function send403(req, res, err, cb) {
  console.log('Forbidden');
  res.end();
}

然后我在ForbiddenError事件中使用该函数:

server.on('ForbiddenError', send403);

我希望每次服务器收到没有authorization标头的请求时都会执行该功能

server.get('/resource', function (req, res, next) {
  if(typeof req.headers['authorization'] === 'undefined') {
    return next(new restify.ForbiddenError());
  }
  else {
    // HTTP 200
  }
});

每次我尝试访问 url 时,我都会收到默认的 restify JSON 消息。

仅供参考,我已经为 404 错误尝试了相同的方法,并且有效

server.on('NotFound', send404);

每次我尝试向不存在的 url 发送请求时,都会执行send404函数。

我想这可能就是你要找的。 我注意到在“server.on”语句中,restify 不需要“错误”部分。 下面是一个完整的工作示例。

'use strict';
var restify = require('restify');
var server = restify.createServer();

server.on('Forbidden', send403);

server.get('/resource', function(req, res, next){
    if(typeof req.headers['authorization'] === 'undefined') {
        next(new restify.ForbiddenError());
    }
    else {
        // HTTP 200
    }
});

function send403(req, res, err, cb){
    console.log('Log something here');
    return cb();
}

server.listen(9000);
console.log('listening on port 9000');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM