重定向相对路径Express.js出错了

时间:2018-05-01 10:48:54

标签: javascript express

重定向方法无法按预期工作。它无法获取具有相对路径的页面。如果绝对是罚款。比如https://www.google.com。但是当我把相对路径index.html与post.html目录相同时。它无法取得它。如果输入表单值为admin,则从代码中将页面重定向到index.html

节点脚本

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error) 
{
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id FROM products where name='$prod'";
$result = $conn->query($sql);
if (!$result)
  {
  echo("Error description: " . mysqli_error($conn));
  }
// if there is one record only
$row = $result->fetch_assoc();
$id = ($row['id']);
echo $id;

//if there is a multiple records
 while($row = $result->fetch_assoc()) 
 {
        echo "id: " . $row["id"]. "<br>";
 }

html脚本

const express = require('express');
const app = express();
const http = require('http').Server(app);
const bodyParser = require('body-parser');

app.use(express.urlencoded({ extended: true }));

app.get('/', (req, res) => res.sendFile(__dirname + '/post.html'));

app.post('/', function(req, res){
    var username = req.body.username;
    if(username == 'admin'){
    res.redirect(__dirname + '/index.html');
    }
    res.end();
});

http.listen(80, function(){
    console.log('Listening on *:80');
    });

3 个答案:

答案 0 :(得分:1)

首先,您需要将index.html文件公开给客户,现在他们只能访问post.html

为此,您可以为索引页面添加新路由,也可以使用express.static()来提供文件。

如果您想使用第一个解决方案,请添加如下路线:

app.get('/index', (req, res) => res.sendFile(__dirname + '/index.html'));

然后在下一个块中重定向到它:

app.post('/', function(req, res){
    var username = req.body.username;
    if(username == 'admin'){
      res.redirect('/index');
    }
    res.end();
});

如果您想使用express.static(),您可以这样做:

将您希望客户端访问的文件放在应用程序根目录(节点脚本所在的位置)的另一个目录中(这通常称为&#34; public&#34;)。之后使用express.static()函数告诉Express像Apache服务器那样提供目录:

app.use(express.static(__dirname + 'public'))

之后,您可以将客户端重定向到/index.html

app.post('/', function(req, res){
    var username = req.body.username;
    if(username == 'admin'){
      res.redirect('/index.html');
    }
    res.end();
});

答案 1 :(得分:0)

我认为您并不了解redirect的工作原理。只需查看文档expressjs.com#res.redirect即可。 在那里,您可以发现只能使用redirect方法从一个路径移动到另一个路径。

无论如何,你错误地使用了它。

此代码不起作用:res.redirect(__dirname + '/index.html');

答案 2 :(得分:0)

  __dirname + '/index.html'

这将是:

 "C:/some/crazy/path/index.html"

现在这将发送给客户端。而且这不仅可以通过线路访问本地文件系统,原因很简单。因此,不是重定向到某个文件(不起作用),而只是重定向到服务器托管的URL(提示:index.html不是路由):

 res.redirect("/");
相关问题