【问题标题】:node.js express handling other .get triesnode.js 快速处理其他 .get 尝试
【发布时间】:2016-08-25 21:51:32
【问题描述】:

目前我正在使用

app.get('/prices/all', function (req, res) {
   fs.readFile( __dirname + "/" + "data.json", 'utf8', function (err, data) {
        res.set({ 'content-type': 'application/json; charset=utf-8' })
        res.end( data );
   });
}) 

这一切都很好,但是如果用户尝试使用任何其他 url,例如,我想发送一个错误 json 响应。 /价格自己。例如:

{status:"failed", error:"wrong get attempt"}

这是托管在子域上的,因此 api.sitename.com/# 的所有链接都需要删除,但 /prices/all

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    Express JS 允许您为未映射的路由定义自定义错误处理。因此,您可以创建一个函数,当请求的资源不存在 404 时,该函数将响应您指定的 JSON。

    app.use(function(req, res) {
       res.send('{"status":"failed", "error":"wrong get attempt"}', 404);
    });
    

    http://expressjs.com/en/guide/error-handling.html

    要进一步了解为什么这是处理 404 响应的首选方式,请参见下文:

    http://www.hacksparrow.com/express-js-custom-error-pages-404-and-500.html

    【讨论】:

      【解决方案2】:

      将此添加为您的最后一条路线

      app.use(function(req, res, next) {
        res.status(404).json({status:"failed", error:"wrong get attempt"});
      });
      

      您的路线文件应如下所示

      app.get('/prices/all', function (req, res) {
         fs.readFile( __dirname + "/" + "data.json", 'utf8', function (err, data) {
              res.set({ 'content-type': 'application/json; charset=utf-8' })
              res.end( data );
         });
      }) 
      
      app.use(function(req, res, next) {
        res.status(404).json({status:"failed", error:"wrong get attempt"});
      });
      

      【讨论】:

      • 我试过你的,但它只是说 GET 无效而没有发送错误消息。
      • @Matt 你要求一个 json,另一个答案是返回一个字符串。
      猜你喜欢
      • 2021-09-23
      • 2019-02-09
      • 1970-01-01
      • 2021-08-03
      • 2014-02-19
      • 2019-04-08
      • 1970-01-01
      • 2017-01-08
      相关资源
      最近更新 更多