如何解决express res.redirect() 在登录时不起作用
假设我希望服务器在登录成功后将用户链接到 admin.html 页面,所以我在 '/login' 路由处理程序(POST 方法)中使用了 put res.redirect('/admin.html')。>
但是,服务器不会将用户定向到 admin.html 页面。服务器只会在用户输入用户名和密码后每次点击登录按钮时将用户重定向到主页面(路由“/”)。它无法将我重定向到 admin.html
页面。
admin.html 存储在“protected”文件夹中,我已经应用了 app.use(isLoggedIn,express.static('protected')) 所以服务器应该能够访问它。
import express,{NextFunction,Request,Response } from "express";
import expressSession from "express-session";
import path from "path";
import bodyParser from "body-parser";
import jsonfile from "jsonfile";
import multer from "multer";
const storage = multer.diskStorage({
destination: function (req,file,cb) {
cb(null,path.resolve("./public/uploads"));
},filename: function (req,`${file.fieldname}-${Date.Now()}.${file.mimetype.split("/")[1]}`);
},});
const upload = multer({ storage });
const app = express();
app.use(
expressSession({
secret: "Memo wall is fantastic",resave: true,saveUninitialized: true,})
);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
interface Memo {
content: String;
image: String;
}
interface User {
username: String;
password: String;
}
app.use((req: Request,res: Response,next: NextFunction) => {
if (req.session["counter"]) {
req.session["counter"] += 1;
} else {
req.session["counter"] = 1;
}
console.log(`req.session['counter'] is ${req.session["counter"]}`);
next();
});
app.use(function(req: Request,next:NextFunction){
const Now = new Date();
// const date = Now.toISOString().replace('T','').replace(/\..*/g,'');
const date = formatDate(Now);
console.log(`[${date}] Request ${req.path}`);
next();
});
app.post("/memos",upload.single("image"),async (req,res) => {
const memos = await jsonfile.readFile("./memos.json");
const memo = req.body;
if (req.file) {
memo.image = req.file.filename;
}
memos.push(memo);
await jsonfile.writeFile("./memos.json",memos,{ spaces: 4 });
// memos.push(req.body);
// console.log(req.body)
res.redirect("/"); //URL vs file path
// memos.push(req.body);
});
app.get("/memos",res) => {
const q = req.query.q;
const memos: Memo[] = await jsonfile.readFile("./memos.json");
if (!q) {
res.json(memos);
} else {
const filteredMemos = memos.filter((memo) => memo.content.includes(q +''));
res.json(filteredMemos);
}
});
app.post('/login',async(req,res)=>{
console.log(req.body);
const users:User[] = await jsonfile.readFile("./users.json");
const userFound = users.find(function(user){
return user.username === req.body.username
&& user.password === req.body.password;
})
if(userFound){
req.session['user'] = userFound;
res.redirect('/admin.html');
}else{
res.redirect('/');
}
});
const isLoggedIn = (req:Request,res:Response,next:express.NextFunction)=>{
if(req.session['user']){
next();
}else{
res.redirect('/');
}
}
app.use(express.static("public"));
app.use(isLoggedIn,express.static('protected'));
app.use(function (req: Request,res: Response) {
res.sendFile(path.resolve("./public/404.html"));
});
app.listen(8080,function () {
console.log("Listening at http://localhost:8080");
});
function formatDate(Now:Date){
return Now.getFullYear()+"-"+
(Now.getMonth()+1 +"").padStart(2,"0") + "-" +
(Now.getDate()+"").padStart(2,"0")+" "+
(Now.getHours()+"").padStart(2,"0")+":"+
(Now.getMinutes()+"").padStart(2,"0")+":"+
(Now.getSeconds()+"").padStart(2,"0");
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。