【问题标题】:Res.render() not renderingRes.render() 不渲染
【发布时间】:2016-03-22 00:19:32
【问题描述】:

我有这条似乎拒绝渲染翡翠模板的快速路线。当我输入错误的玉模板字符串时,我通常找不到正在呈现给浏览器的文件。

但是当我选择正确的时候,什么都没有发生......

此外,当我在res.render() 之后添加res.status(500).send() 时,我最终会收到 500 错误或我选择放入其中的任何其他代码。

这是怎么回事?

 app.post('/stuff/new', function (req,res){


    Stuff.findById(req.body.booking_id, function(err, stuff){
      if(err){ console.log("Err", err)}

      else if (booking) {

        Thungs.findById(req.body.user_id, function(err, thung){
          user.stuff.push(req.body.things);
          user.save();
        });

        Thingers.findById(req.body.center_id, function(err, thinger){
          center.stuff.push(req.body.things);
          center.save();
        });

        stuff.prop = 'thing';
        stuff.save(function(err, result){
          if (err) { console.err("err", err) }
          else {

            res.render('booking/thank_you', {
              url: req.url,
              id: "thank_you"
            }, function(err, html){
              if (err) { console.err("ERR", err) }
              else {
                res.send(html);
              }
            });
            res.status(500).send();

          }
        });
      }
    })
  });

【问题讨论】:

标签: javascript node.js express


【解决方案1】:

如果您只想渲染模板,则不需要res.send(html);,只需从res.render() 中删除回调,它应该可以正常工作。而且当res.status(500).send(); 显示500 时,因为在res.render()res.send() 之后的语句将执行后连接不会终止,您可以使用return res.render()return res.send() 然后控制不会转到res.status(500).send()

希望对你有帮助:)

【讨论】:

  • 我不确定你在说什么,res.status(500).send() 显示为 500,因为我在里面放了 500
【解决方案2】:

整个stuff.save() 回调不正确,因为您永远不会返回res.render() 的结果。但是,您的 res.render() 会被执行,因为您将回调传递给 res.render(),它不会自动响应请求。

res.render(view [, locals] [, callback])

渲染一个视图并将渲染后的 HTML 字符串发送给客户端。可选参数:

  • locals,一个对象,其属性定义视图的局部变量。

  • callback,回调函数。如果提供,该方法将返回可能的错误和呈现的字符串,但不执行自动响应。当发生错误时,该方法在内部调用 next(err)。

由于res.render() 函数没有阻塞,您的stuff.save() 回调将继续执行到res.status(500).send() 并做出响应。最终,您的视图不会被渲染,并且您的左侧会收到 500 Internal Server Error 作为响应。

重要的是要注意,在您想要在响应后停止执行的响应时,在几乎所有情况下,return 都是“最佳实践”。唯一不想在回复时使用 return 的情况是,如果您之后需要执行某种类型的清理例程。

以下代码在成功时正确返回res.render(),在发生错误时正确返回res.status(500)

stuff.save(function(err, result){
  if (err) { 
    console.err("err", err) 

    // An error occurred, stop execution and return 500
    return res.status(500).send();
  } 

  // No error occurred, attempt to render the view 
  // and return the outcome of the rendering to the callback
  res.render('booking/thank_you', {
      url: req.url,
      id: "thank_you"
    }, function(err, html){
      if (err) { 
        console.err("ERR", err) 

        // An error occurred, stop execution and return 500
        return res.status(500).send();
      }

      // Return the HTML of the View
      return res.send(html);
    });
  }
});

【讨论】:

  • 在所有其他路线上都能正常工作
  • 你试过我的建议了吗?
猜你喜欢
  • 1970-01-01
  • 2019-02-05
  • 1970-01-01
  • 2014-04-07
  • 2013-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
相关资源
最近更新 更多