在 express 中,我如何将用户重定向到外部 url?

In express how do I redirect a user to an external url?

我有一个使用 node.js 和 braintree 的支付系统,当支付成功时我想将用户发送到后端。我的后端设置在别处。

我试过了

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

所以window.location显然是不可用的。我想不出任何重定向用户的方法吗?

你可以做到

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

快递文件:https://expressjs.com/en/api.html#res.redirect

我只是遇到了同样的问题,通过添加 "next" 解决了这个问题。我使用路由器,所以也许你有和我一样的问题?没有下一个,我得到关于没有渲染引擎的错误...很奇怪

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;

所选答案对我无效。它将我重定向到:locahost:8080/www.google.com - 这是胡说八道。

301 Moved Permanently 需要包含在 res.status(301) 中,如下所示。

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

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

})

您的情况与您相同,因为您的后端在别处。

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

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

})

您需要包含状态 (301)

None 这些对我有用,所以我用以下结果欺骗了接收客户端:

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

有人会说如果noscript在这不行,但实际上哪个站点没有使用它。

将用户重定向到外部 URL 非常简单。

res.redirect('enter the URL here');

使用这个代替你可以简单地被重定向:

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

确保在 https 上添加其余状态不是必需的,用户名说这是胡说八道:@AIon :)