【发布时间】:2020-07-06 06:37:32
【问题描述】:
我目前正在创建一个应用程序,我使用 MongoDB 存储登录数据,使用 nodejs 创建 API 和前端 JS HTML 来显示页面。我正在创建用户,我通过 fetch ajax POST 调用将电子邮件 ID 和密码传递给后端节点服务器。在 DB 中创建用户的后端 api 路由。我想在创建用户后重定向到不同的页面。我怎样才能做到这一点?她是我的代码 sn-p。
//前端获取调用
async function createUser(email , password) {
return fetch("http://localhost:3000/user",
{
// Adding method type
method: "POST",
// Adding body or contents to send
headers :{
"content-type": "application/json"
},
body: JSON.stringify({
"userId" : email.value,
"password" : password.value
})
});
}
//后端代码
app.post('/user', async (req, res) => {
// res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Methods", "POST,OPTIONS");
const {error} = validate(req.body);
if (error) {
return res.status(400).send(error.details[0].message);
}
let user = await User.findOne({userId : req.body.userId});
if(user) return res.status(400).send("User already registered");
let newUser = new User (
{
userId : req.body.userId,
password : req.body.password
}
);
newUser = await newUser.save();
res.redirect('/logged');
//res.send(newUser)
//res.send("<h1>Hi</h1>");
//res.sendFile((path.join(__dirname+'/loggedon.html')));
//res.send("<h1>Hi</h1>");
}
);
app.get('/logged' , function(req, res){
res.send("<h1>Hi</h1>");
// res.setHeader(200 , 'Content-Type' , 'text/html');
// fs.readFile('./loggedon.html', function(err , data){
// res.write("<h1>Hi</h1>");
// })
});
我正在检查仅发送 HI。但这在本地服务器上可以正常工作。但是我将如何将数据发送到前端。请告诉我。注释行是我已经尝试过的。
【问题讨论】:
标签: javascript html node.js express