简体   繁体   中英

Redirect after already used response Node js

I want to render some page and after certain amount of seconds it needs to be redirected to another page. However, I get an "Can't set headers after they are sent." From what I read, the response should be used only once, though I'm not sure if this is true. I would appreciate any help or solution to this particular problem.

app.get('/', function (req, res) {
    var message = req.flash();
    res.render('index', { message: req.flash('message'), hassError: message.length > 0} );
});

app.get('/error', function (req, res) {
    var timeout = 3000;

    setTimeout(function (err) {
        console.log('finished');
        if (err)
            throw err;
        console.log('################');
        res.redirect('/');
    }, timeout);
    res.render('partials/404');
});

"finished" gets printed and then it throws error, but not the err specified in callback.

You can't use this approach - rendering means sent to browser with headers, then the HTTP request is closed by browser. You can't send a second response.

You'll have to do the timeout logic in JavaScript on the page, not server:

<script>
  var timeout = 3000;

  setTimeout(function () {
     window.location = "http://www.yoururl.com";
  }, timeout);
</script>

You can't send multiple responses to a single request. It's like if someone asks you for a burger, you give them a burger, and they walk away. Some time later you lob another burger at the back of their head. They aren't going to catch it.

In this case, you'll need to handle redirecting on the client-side. If this is just a regular page render, you can use the refresh attribute of a meta tag.

<meta http-equiv="refresh" content="2; url=http://path/to/my/page/" />

If this is an AJAX request, you'll need to have the client perform the redirect after a delay.

您尝试发送的重定向应该在用户访问服务器时在服务器端完成,或者在 404 页面加载后在浏览器上完成。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM