Node.JS 重定向没有效果,也没有错误

问题描述 投票:0回答:1

我正在使用 Node.JS 制作一个应用程序,当我尝试将用户从登录页面重定向到另一个页面时,没有任何反应。

我使用了此登录功能,其中使用

res.redirect(307, "/home/userPAGE")
来重定向用户:

const login = asyncHandler (async (req, res) => {
    const {email, password} = req.body;
    if (!email || !password){
        res.status(400);
        throw new Error("Email or password not provided");
    }
    const user = await User.findOne({email});
    if (user && (await bcrypt.compare(password, user.password))) {
        const accessToken = jwt.sign({
            user: {
                username: user.id,
                email: user.email,
                id: user.id
            },
        }, process.env.ACCESS_TOKEN_SECRET,
        {expiresIn: "30m"});
        console.log("Logged in!");
        res.redirect(307, "/home/userPAGE");
    }
    else {
        res.status(400);
        throw new Error("Email or Password is not valid");
    }

});

然后,这个路径应该加载我的 userpage.html 文件:

app.use("/home/userPAGE", (req, res) => {
    console.log("HERE")
    res.sendFile(path.join(__dirname, "./public/userpage.html"));
});

但事实并非如此。如果我查看日志,我会看到

HERE
,但之后什么也没有发生。

我看过其他人的帖子,但看起来我的代码与解决方案中的人类似,所以我对问题是什么感到困惑。

这是答案之一:

var express = require("express");
var bodyParser = require("body-parser");

var app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + "/public/arena.html"));

app.get('/', function(req, res) {
  res.sendFile(__dirname + "/public/index.html");
});

app.get('/arena', function(req, res) {
  res.sendFile(__dirname + "/public/arena.html");
});

app.post('/login', function(req, res) {
  var username = req.body.username;
  console.log("User name = " + username);

  // Note how I'm redirecting the user to the /arena URL.
  // When you issue a redirect, you MUST redirect the user
  // to a webpage on your site. You can't redirect them to
  // a file you have on your disk.
  res.redirect("/arena");
});

app.listen(3000);
javascript html node.js
1个回答
1
投票

您有

app.use
,因为您正在定义一条路线,所以它需要是
app.get("/home/userPAGE", (req, res) => {...

© www.soinside.com 2019 - 2024. All rights reserved.