有没有办法动态使用带有url参数的res.render?

时间:2015-01-04 19:56:29

标签: javascript node.js express

我正在尝试以?parameter=12345的形式动态加载包含不同网址参数的网页,但我得到了响应Failed to lookup view "account/signup?parameter=12345" in views directory,这可能意味着它确实在寻找一个完全匹配的查看模板,包括参数方面。有没有办法可以在以下注册代码中使用该参数呈现页面:

exports.getSignup = function(req, res) {
  if (req.user) return res.redirect('/');
  try{
    headerString = req.headers.referer;
    headerString =  headerString.match(/\?(.*)/)[0] 
  }catch(e){
    console.log(e)
  }

  res.render('account/signup' + headerString, {
    title: 'Create Account',
    savedTripId: headerString
  });
};

1 个答案:

答案 0 :(得分:1)

哟可以在不提及网址

中的headerString的情况下呈现
exports.getSignup = function(req, res) {
  if (req.user) return res.redirect('/');
  try{
    headerString = req.headers.referer;
    headerString =  headerString.match(/\?(.*)/)[0] 
  }catch(e){
    console.log(e)
  }

  res.render('account/signup', {
    title: 'Create Account',
    savedTripId: headerString
  });
};

因为看起来你正在使用JADE,你可以在客户端做这样的事情

form(action="/formsubmit/#{headerString}")
    // form elements
    .
    .
    .

这将其呈现为

form(action="/formsubmit/1234")
    // form elements
    .
    .
    .

然后,当提交表单时,您可以在服务器端获取标题,如下所示

app.post('/formsubmit/:headerString', function(req, res){

    var tripId = req.params.headerString;
    var formData = req.body; // if you are using body parser middleware
    // now you know which tripId has to be saved and have the form data. Perform actions accordingly

})