我使用的技术有:Nodejs、Express、MySQL、EJS。
我在做什么:
有一个 app.get 从 MySQL 获取所需的数据(帖子),然后使用该数据呈现一个文件
app.get("/" + element.name, function(req, res){
connection.query(`SELECT * FROM sub ${element.name} posts`, function(error, result) {
if(error) {
console.log(`Nick error`)
} else {
console.log(`Works get !`)
posts = result;
}
});
res.render("sub" + element.name, {posts:posts}), console.log(posts + " Here")
当有人访问该 url 时,将呈现该数据(帖子)并使用该数据发出 FETCH POST 请求(我使用的是它的长度),
// Before this, the data gets mapped into the variable called "final"
console.log("!!!###")
console.log(`Above the FETCH`)
console.log(`yes in normal position 1 `)
console.log(` BTW ${JSON.stringify(final)}`) // I CAN SEE THE NEW POST HERE #########################
fetch(`/ookook`, { method: 'POST', body: JSON.stringify(final), headers: new Headers({ "Content-Type": "application/json" }) })
.then(res => res.json())
.then(jsonRes => {
console.log(`yes in normal position 2 `)
console.log(`DRAGON BTW ${JSON.stringify(final)}`) // I CAN SEE THE NEW POST HERE ###############################
})
然后 POST 请求看到数据(帖子)的长度,并为每个数据(它是一个对象数组的数组,所以它为每个数组数组执行此操作)创建一个 app.get 路由,url 是“/pagename/2"(数字递增)
app.post("/" + element.name, function(req, res) {
for(let i = 0; i < req.body.length; i++) {
for(let b = 0; b < req.body[i].length; b++) {
console.log(req.body[i][b].id)
let posts = req.body[i];
console.log(posts) // I CAN SEE THE NEW POST HERE ###########################
console.log("in app.post friendo")
app.get(`/${element.name}/${i + 2}`, function(req, res) {
res.render("sub"+ element.name, { posts:posts})
})
}
}
res.status(200).json({voteNum: 5}) // Ignore the voteNum
});
问题:当我创建一个新帖子时,它会将它提供给我的数据库,我可以使用 console.log 在我的客户端和服务器端看到它,但是它不会呈现它。为了让我看到帖子,我必须重新启动我的服务器。
我在代码中写了“//I CAN SEE THE POST HERE #############
”,我可以在 console.log 中看到新帖子(服务器/客户端)但它没有被渲染
最佳答案
当启动脚本时,启动服务器时,app
即 express
及其所有中间件都已设置。
除非重启服务器,重置 app
,否则您的更改将不起作用。
我认为你的概念不正确
首先
也许可以试试这样的东西
let list = [];
//list is the data in posts, you can init it by query the DB.
app.get('/:elementname' ,()=>{
//check whether req.params.elementname match list
//if match, it is a validate url, or else 404 NOT FOUND=>call next()
})
app.post('/newPostName', ()=>{
//add new post to DB and update list.
})
第二
顺便说一下,
你最好检查一下 connection.query
是否是一个异步函数。
如果是,代码应该是
connection.query('query...' ,()=>{
//...
res.render()
})
不是
connection.query('query...' ,()=>{
//...
})
res.render()
关于javascript - 客户端和服务器端都有更新的数据,但渲染不显示更新的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49858169/