首页 > 解决方案 > 当 html 文件存在时,重定向在 express js 中不起作用

问题描述

当用户使用以下代码提交表单时,我试图在 express.js 中进行重定向。

app.post('/thank-you', function(req, res){
    res.cookie('form_filled' , 'true');
    res.redirect('/thank-you.html');

 });

此代码工作正常,重定向到thank-you.html 文件。我还想检查 cookie(form_filled) 是否存在于对thank-you.html 的 GET 请求中。代码如下。

app.get("/thank-you.html", function(req, res) {
    //Condition to check the cookie
    res.redirect('/'); //If cookie not present
  });

检查cookie的代码我还没有写,只是先用上面的代码来验证重定向。但它不起作用。

在目录中没有thanks.html 文件的情况下尝试使用以下代码。

app.post('/thank-you', function(req, res){
    res.cookie('form_filled' , 'true');
    res.redirect('/thanks.html');

 }); 

app.get("/thanks.html", function(req, res) {
    console.log("Test");
    res.redirect('/');
  });

标签: express

解决方案


参考这篇文章,我认为这会对你有所帮助。尝试使用 sendFile 或 ejs、pug、hbs 等视图来呈现 html 文件。

发布关于在 express js 中渲染 html 文件的帖子

检查路线内的cookie,也改变路线。例如,将 /index.html 更改为 /index 。


推荐阅读