如何将用户的浏览器 URL 重定向到 Nodejs 中的不同页面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11355366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:59:43  来源:igfitidea点击:

How to redirect user's browser URL to a different page in Nodejs?

httpnode.jsredirectpostwebserver

提问by Tanaki

In the application I'm trying to write, the main page (http://localhost:8675) has the following form:

在我尝试编写的应用程序中,主页 ( http://localhost:8675) 具有以下形式:

<form action='/?joinnew' method='post'>
  <button>Start</button>
</form>

Here is the code in server.js:

这是 server.js 中的代码:

http.createServer(function(request, response) {
  var root = url.parse(request.url).pathname.split('/')[1];
  if (root == '') {
    var query = url.parse(request.url).search:
    if (query == '?joinnew') {
      var newRoom = getAvaliableRoomId(); // '8dn1u', 'idjh1', '8jm84', etc.
      // redirect the user's web browser to a new url
      // ??? How to do.  Need to redirect to 'http://whateverhostthiswillbe:8675/'+newRoom
...
}}}

I would love if there were a way to do it where I didn't have to know the host address, since that could be changing.

如果有一种方法可以在我不必知道主机地址的情况下做到这一点,我会很高兴,因为这可能会发生变化。

The 'http' object is a regular require('http'), NOT require('express').

'http' 对象是一个普通的 require('http'),而不是 require('express')。

回答by ebohlman

response.writeHead(301,
  {Location: 'http://whateverhostthiswillbe:8675/'+newRoom}
);
response.end();

回答by David Seholm

For those who (unlike OP) are using the expresslib:

对于那些(与 OP 不同)使用express库的人:

http.get('*',function(req,res){  
    res.redirect('http://exmple.com'+req.url)
})

回答by ciso

OP: "I would love if there were a way to do it where I didn't have to know the host address..."

OP:“如果有一种方法可以在我不必知道主机地址的情况下做到这一点,我会很高兴……”

response.writeHead(301, {
  Location: "http" + (request.socket.encrypted ? "s" : "") + "://" + 
    request.headers.host + newRoom
});
response.end();

回答by agravat.in

In Express you can use

在 Express 中,您可以使用

res.redirect('http://example.com');

res.redirect('http://example.com');

to redirect user from server.

从服务器重定向用户。

To include a status code 301 or 302 it can be used

要包含状态代码 301 或 302,可以使用

res.redirect(301, 'http://example.com');

回答by vintagexav

If you are using Express, the cleanest complete answer is this

如果您正在使用Express,最干净的完整答案是这个

const express = require('express')
const app     = express()

app.get('*', (req, res) => {
  // REDIRECT goes here
  res.redirect('https://www.YOUR_URL.com/')
})

app.set('port', (process.env.PORT || 3000))
const server = app.listen(app.get('port'), () => {})

回答by Codemaker

You can use res.render() or res.redirect() method to redirect to another page using node.js express

您可以使用 res.render() 或 res.redirect() 方法使用 node.js express 重定向到另一个页面

Eg:

例如:

var bodyParser = require('body-parser');
var express = require('express');
var navigator = require('web-midi-api');
var app = express();

app.use(express.static(__dirname + '/'));
app.use(bodyParser.urlencoded({extend:true}));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);

app.get('/', function(req, res){
    res.render("index");
});

//This reponds a post request for the login page
app.post('/login', function (req, res) {
    console.log("Got a POST request for the login");
    var data = {
        "email": req.body.email,
        "password": req.body.password
    };

    console.log(data);

    //Data insertion code
    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://localhost:27017/";

    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db("college");
        var query = { email: data.email };
        dbo.collection("user").find(query).toArray(function(err, result) {
            if (err) throw err;
            console.log(result);
            if(result[0].password == data.password)


 res.redirect('dashboard.html');
            else


 res.redirect('login-error.html');
            db.close();
        });
    });

});


// This responds a POST request for the add user
app.post('/insert', function (req, res) {
    console.log("Got a POST request for the add user");

    var data = {
        "first_name" : req.body.firstName,
        "second_name" : req.body.secondName,
        "organization" : req.body.organization,
        "email": req.body.email,
        "mobile" : req.body.mobile,
    };

    console.log(data);

    **res.render('success.html',{email:data.email,password:data.password});**

});


//make sure that Service Workers are supported.
if (navigator.serviceWorker) {
    navigator.serviceWorker.register('service-worker.js', {scope: '/'})
        .then(function (registration) {
            console.log(registration);
        })
        .catch(function (e) {
            console.error(e);
        })
} else {
    console.log('Service Worker is not supported in this browser.');
}


// TODO add service worker code here
if ('serviceWorker' in navigator) {
    navigator.serviceWorker
        .register('service-worker.js')
        .then(function() { console.log('Service Worker Registered'); });
}

var server = app.listen(63342, function () {

    var host = server.address().host;
    var port = server.address().port;

    console.log("Example app listening at http://localhost:%s", port)
});

Here in the login section, If the email and password matches in the database then the site is directed to dashbaord.html otherwise we will show page-error.html using res.redirect() method. Also you can use res.render() to render a page in node.js

在登录部分,如果电子邮件和密码在数据库中匹配,则站点将定向到 dashbaord.html,否则我们将使用 res.redirect() 方法显示 page-error.html。您也可以使用 res.render() 在 node.js 中渲染页面