所以我在这个问题上停留了一段时间,我认为这可能与内容类型有关,但我不确定,我会把它留给大家。
script.js
let pass = {username: username, password: password};
fetch("/login",{
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(pass)
}).catch(function (err) {
alert("Something's wrong :(");
});
server.js
app.set('view engine', 'pug');
app.post('/login', function (req, res) {
console.log(req);
console.log(req.body);
res.render('main',{
username: 'aaaaaa',
favorites: ''
});
});
如果我尝试更改内容类型,则主体会变空,并且渲染仍然无法执行任何操作。
如果我从index.html运行常规的GET请求(不使用访存),它将按预期运行渲染。只需使用后一个将数据传递到哈巴狗。
app.get('/createUser', function (req, res){
res.render('main',{
username: 'aaaaaa',
favorites: ''
});
res.sendFile(__dirname + '/' + 'public/createUser.html');
});
预先感谢
编辑:
还尝试使用下面的中间件和会话,结果相同。无法呈现页面。如果这是我需要的,则不确定如何从帖子更改为获取请求。
app.use(session({
secret: 'tarter sauce',
resave: false,
saveUninitialized: true
}))
app.post('/login', log, test, main);
function log(req, res, next) {
//console.log(req);
req.session.valid = false;
console.log(req.body);
const input = req.body;
console.log(input);
console.log(input.username);
fs.readFile('users.json', (err,data)=>{
if(err) throw err;
const users = JSON.parse(data);
//console.log("data "+data);
//console.log(req.headers['content-type']);
if (users.hasOwnProperty(input.username)){
//console.log("is a user");
if(users[input.username].password==input.password){
//console.log("login success");
const response = {
username: users[input.username].username,
favorites: users[input.username].favorites
};
req.session.username = users[input.username].username;
req.session.favorites = users[input.username].favorites;
req.session.valid = true;
}
}
//console.log("next");
next();
});
}
function test(req, res, next){
//console.log("test");
next();
}
function main(req, res){
//console.log(req.session.username);
//console.log("render");
res.send();
res.render('main', {
username: "req.session.username",
favorites: "req.session.favorites"
});
res.end;
};