【问题标题】:How to end a bad request silently如何默默地结束一个糟糕的请求
【发布时间】:2020-12-13 16:30:45
【问题描述】:

如何结束 nodejs 中的错误请求。例如:

http.createServer((req, res) => {
    //lets say a user sends a bad request
    checkIfRequestIsGoodorBad()
    //After finding out that the request is bad, how do i terminate it before it reaches doSomething()
    doSomething()
}).listen()

【问题讨论】:

  • return 语句(在 if 块内)应该这样做
  • 如果return语句在回调函数中会发生什么?
  • 你想返回一个http错误响应给客户端还是直接终止连接?
  • 我想发送响应然后终止连接

标签: javascript node.js http server request


【解决方案1】:

这应该有效: (如果您需要回调,只需将函数交换为异步)

function checkIfRequestIsGoodorBad(req,res){
    if(req.url==="/naughty"){
        return "Bad"
    }else{
        return "Good"
    }
}
http.createServer((req, res) => {
    //lets say a user sends a bad request
    if(checkIfRequestIsGoodorBad(req)==="Good"){//passing req as an argument
        doSomething()
    }else{
        handleBadRequest()
    }
}).listen()

【讨论】:

    【解决方案2】:
    • checkIdRequestisGoodOrBad 返回一个布尔值
    • 测试if布尔值是否为真
    • if true 使用 return 关键字
    const checkIfRequestIsBad = (request) => {
        // your business logic
        return true // return true or false
    }
    http.createServer((req, res) => {
        if(checkIfRequestIsBad(req)) return;
    
        doSomething()
    }).listen()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-29
      • 1970-01-01
      • 2022-07-13
      • 2014-06-30
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      相关资源
      最近更新 更多