如何在锚点渲染 EJS

How to render EJS at anchor

我想做点什么(也许有一个我没有看到的更简单的方法)但基本上我想做的是有一个带有 Mailchimp 注册表格的 EJS 文件,当注册得到填充然后它重定向到同一个 EJS 文件,但这次使用一个变量将文本添加到 HTML.

基本上,当用户输入电子邮件时,我们会将他重定向到同一部分,但这次它会添加一个带有文本 "Thank you, we've got your email, we'll get in touch with you soon" 的 p 标签,这是我的方法:

app.post('/', (req, res) => {
  mailchimp.post('/lists/' + process.env.MAILCHIMP_LIST + '/members', {
      email_address: req.body.email,
      status: 'subscribed'
    }, (err) => {
    if(err){
      console.log(err.title);
      if(err.title == 'Member Exists'){
        res.redirect('/#signup', {
          Status: "Thank you, we've got your email, we'll get in touch with you soon"
        })
      }else{
        res.redirect('/#signup', {
          Status: "We're having problems signing you up, if the problem persists send an email to hello@hibuddie.com"
        })
      }
    }
  });
  res.redirect('/#signup', {
    Status: "Thank you, we've got your email, we'll get in touch with you soon"
  });
});

然而,当我尝试这样做时,我的控制台出现错误:

express deprecated res.redirect(url, status): Use res.redirect(status, url) instead app.js:45:7

我知道重定向可能不适用于 EJS,但我不知道该怎么做,所以它将用户重定向到某个 ID 的同一个 EJS 文件,在这种情况下说 /#signup。

请原谅我糟糕的代码,我要开始写了,哈哈。

您可以通过两种方式完成:

您可以使用 rendering 而不是 redirecting,并将变量添加到渲染函数。

// pass a local variable to the view
res.render('user', { name: 'Tobi' }, function (err, html) {
  // ...
})

并处理视图文件中的变量。 您还可以发送一个 anchor 名称作为变量并添加一些 javascript 来处理它。喜欢:

res.render('user', { anchor: 'signup' }, function (err, html) { ... });

并在模板文件中添加一些javascript,

window.onload = function (event) {
    window.location.hash = "#{{anchor}}";
};

,如果你使用Ajax调用来命中api你可以return这样的状态,

res.json({
    success: true,//or false
    data: {
        Status: "some text"
    }
})

并在前端使用Javascript处理它。