在我的网站上,当用户单击按钮时,一些用户的数据将存储在数据库中,然后我希望服务器将通知数据发送到Javascript前端文件以更改UI。
现在,Js文件(index.js)在网站加载后立即接收数据(总是false)。我希望只有在服务器上准备好数据时才能接收到它。
我找了很多东西,却找不到解决问题的办法?
(我感谢你的帮助:)
server.js
var requestValidation = false;
app.post("/", function(req, res){
var name = req.body.personName;
var email = req.body.personEmail;
var collabTopic = req.body.collabTopic;
const newUser = new User({ //mongoDB schema
name: name,
email: email,
collabTopic: collabTopic
});
newUser.save(function(err){ //adding data to mongoDB
if(!err){
requestValidation = true;
}
});
});
app.get("/succ", function(req, res){
res.json(requestValidation);
});index.js
const url = "http://localhost:3000/succ";
const getData = async (url) => {
try {
const response = await fetch(url);
const json = await response.json();
console.log(json);
} catch (error) {
console.log(error);
}
};
getData(url);发布于 2022-07-19 06:23:37
我不确定这完全是您想要的答案,但在您重新设计您的方法时,这绝对是一个需要考虑的工具/特性。
app.post("/", async (req, res) => {
let result = await INSERT MONGODB UPDATE OR INSERT FUNCTION;
res.render("YOUR TEMPLATE", result);
});您可能无法即插即用,但是当您完成MongoDB操作时,它会返回一个json对象,并提供一些关于是否成功的详细信息。例如,MongoDB插入操作返回类似的内容(存储在我创建的变量result中)
{ "acknowledged" : true, "insertedId" : ObjectId("5fd989674e6b9ceb8665c57d") }然后你可以根据你的意愿传递这个值。
编辑:这就是tkausl在评论中提到的。
发布于 2022-07-19 08:26:26
下面是一个示例,如果您想使用express和jquery: in express将txt文件的内容传递给客户机:
app.get('/get', (req, res) => {
fs.readFile('test.txt', (err, data) => {
if (err) throw err;
return res.json(JSON.parse(data));
})
})客户端的jquery:
$.getJSON( "http://localhost:3000/get", function( data ) {
geojsondata1 = JSON.stringify(data)
}现在,您可以使用变量数据做任何您想做的事情了。
https://stackoverflow.com/questions/73031854
复制相似问题