89

I have a payment system using node.js and braintree, when the payment is successful I want to send the user to the back end. My back end is setup elsewhere.

I have tried

res.writeHead(301,
  {Location: 'http://app.example.io'}
);
res.end();

So window.location is obviously not available. I cant think of any ways to redirect a user?

Michael Joseph Aubry
  • 12,282
  • 16
  • 70
  • 135

6 Answers6

202

You can do

res.redirect('https://app.example.io');

Express docs: https://expressjs.com/en/api.html#res.redirect

Kaushal28
  • 5,377
  • 5
  • 41
  • 72
TheIronDeveloper
  • 3,294
  • 1
  • 18
  • 17
27

The selected answer did not work for me. It was redirecting me to: locahost:8080/www.google.com - which is nonsense.

301 Moved Permanently needs to be included with res.status(301) as seen below.

app.get("/where", (req, res) => {

    res.status(301).redirect("https://www.google.com")

})

You are in the same situation since your back-end is elsewhere.

AIon
  • 12,521
  • 10
  • 47
  • 73
  • 4
    I was having similar issues and I found that this has to do with `https://` or `http://` needing to be attached to the redirect url. If not it seems to fail. Also adding a `301` results in the redirect url being cached by the browser which means everytime you hit the same url it will redirect you to the first address regardless of whether it could have changed or not. – Y Anderson Apr 20 '18 at 12:34
10
    app.get("/where", (req, res) => {

    res.status(301).redirect("https://www.google.com")

})

You need to include the status (301)

Messivert
  • 103
  • 1
  • 5
2

I just have the same issue and got it work by adding "next". I use routers so maybe you have same issue as mine? Without next, i got error about no render engine...weird

var express = require('express');
var router = express.Router();
var debug = require('debug')('node_blog:server');

/* GET home page. */
router.get('/', function(req, res, next) {
  debug("index debug");
  res.render('index.html', { title: 'Express' });
});

router.post("/", function (req, res, next) {
    //var pass = req.body("password");
    //var loginx = req.body("login");
    //res.render('index.html', { title: 'Express' });
    res.redirect("/users")
    next
});

module.exports = router;
Granit
  • 188
  • 1
  • 11
0

Nobody mentioned this different way of redirect as an answer here, so I write it:

  • To permanent redirect:

    res.redirect(301, 'http://app.example.io');
    
  • To temporary redirect:

    res.redirect(302, 'http://app.example.io');
    // OR
    res.redirect('http://app.example.io');
    
Ramin Bateni
  • 16,499
  • 9
  • 69
  • 98
-12

None of these worked for me, so I tricked the receiving client with the following result:

res.status(200).send('<script>window.location.href="https://your external ref"</script>');

Some will say if noscript is on this does not work, but really which site does not use it.

B--rian
  • 5,578
  • 10
  • 38
  • 89