提问者:小点点

如何将Router.Get内部从Request.Get收到的错误解释为Express.js中的错误?


设计

R作为后端。我使用plumber包公开API。

NodeJSExpressJS应用程序。express检查路由器,然后请求适当的API从R获取数据。

代码

r:

#* @get /reportTypes
#* function to listen to the request and return the results from the csv file. 
#* If the file doesn't exists, it returns an 404 error.
#* @serializer unboxedJSON

function(res, req){
  
  filename <- "file-does-not-exist.csv"
  
  if(file.exists(filename)){
  
      reportTypes <- read.csv(filename)
   
      return(reportTypes) 
  }
  else{
    res$status <- 404
    stop("List of report types could not be loaded.")
  }
  
} 

r错误:

<simpleError in (function (res, req) {    filename <- "ReportTypes1.csv"    if (file.exists(filename)) {        reportTypes <- read.csv(filename)        return(reportTypes)    }    else {        stop("List of report types could not be loaded.")    }})(res = <environment>, req = <environment>): List of report types could not be loaded.>

ExpressJS:

在这里,路由器请求来自给定URL的响应。它确实从plumber接收到错误消息,但我不明白为什么请求会以状态200传递给客户机,而客户机却没有将该错误解释为错误。它将解释为有效的响应。

router.get('/', function (req, res) {

  request.get({ url: 'http://localhost:5762/reportTypes' },
    function (error, response, body) {
      if (!error && response.statusCode == 200) {
        res.send(body);
      }
      else {
        console.log("Error: ", error);
        console.log("body: ", body);
        res.send(body);
      }
    });

});

repressjs中,错误没有从r解释为错误,这是我做错了什么?


共1个答案

匿名用户

使用res.send()express默认情况下将http-status代码设置为200。您可以使用res.status()将代码更改为其他内容。因此,例如,如果要发送500状态,可以执行以下操作:

 res.status(500).send(body);

或者使用后端响应中的状态代码:

 res.status(response.statusCode).send(body);

注意:request-lib是不推荐使用的:https://github.com/request/request#deprecated,因此您可能希望更改为另一个lib。