重定向方法无法按预期工作。它无法获取具有相对路径的页面。如果绝对的话就好了。像https://www.google.com 。但是当我将相对路径index.html 与post.html 目录相同时。它无法获取它。从代码中,如果输入表单值为 admin,它将重定向页面到 index.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');
});
html 脚本
<!DOCTYPE html>
<html>
<head>
<title>My First Application</title>
</head>
<body>
<form method="post">
<input type="text" placeholder="username" name="username"><br>
<input type="submit">
</form>
</body>
</html>
最佳答案
首先,您需要向客户端公开 index.html
文件,现在他们只能访问 post.html
。
为此,您可以为索引页添加新路由,或使用 express.static()
来提供文件。
如果您想使用第一个解决方案,请添加如下路由:
app.get('/index', (req, res) => res.sendFile(__dirname + '/index.html'));
然后在下一个 block 中重定向到它:
app.post('/', function(req, res){
var username = req.body.username;
if(username == 'admin'){
res.redirect('/index');
}
res.end();
});
如果您想使用express.static()
,您可以这样做:
将您希望客户端访问的文件放在应用程序根目录(节点脚本所在的位置)的另一个目录(通常称为“公共(public)”)中。之后,使用 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();
});
关于javascript - 重定向相对路径 Express.js 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50115197/