我是使用NodeJs和MongoDB的初学者。请轻点我。以前,我只开发了一个智力竞赛应用程序的前端部分。现在,我已经开始为它创建后端。以前,我在LocalStorage中存储用户名(从用户在主页上输入(。用户完成测试后,我会在他们的ScoresPage上显示它,并在最后显示他们的分数。
现在我在LocalStorage中既有分数又有用户名。我想把它们存储在我的mongoDB数据库中。我无法通过NodeJS访问LocalStorage。如何通过NodeJS将它们存储在我的数据库中?
我的本地存储
您不能访问服务器端的localStorage,您需要从客户端的localStorage获取值,如下所示:
const userName = localStorage.getItem('name');
const score= localStorage.getItem('mostRecentScore');
然后将其发送到请求主体内的服务器,假设您在前端使用axios:
const serverPathForStoringData = "https://yourServerUrl/storeData";
axios.put(serverPathForStoringData , {
userName,
score
})
.then((response) => {
//do something with the response in the frontend if you want
console.log(response)
}, (error) => {
console.log(error);
});
在服务器端:
router.put("/storeData", (req, res)=>{
const {userName, score} = req.body;
// here you can store userName and score inside the database
res.json({data:"data successfuly stored in DB!"})
});