Post 函数 运行 永远在 JS 中
Post function running forever in JS
我有一个功能设置,主要用于检查某人是否已登录以及他们是否将 1 添加到变量中。问题是当 运行 在诸如邮递员之类的应用程序中它会永远持续下去,而当在浏览器中 运行 它永远不会去.then.
Html
$('.fa-regular.fa-heart').click(function(){
$regular.toggleClass('hide');
$solid.toggleClass('hide');
$added.toggleClass('hide');
$noadded.toggleClass('hide');
console.log("running");
fetch("/articles/popplus/<%= article.id%>", {
method: 'POST',
mode: 'cors',
cache: 'default',
body: JSON.stringify(null)
}).then((data) => {
console.log("data")
console.log(data)
});
})
Node.js
router.post('/popplus/:id', async (req, res, next) => {
var id = req.params.id;
const user = await Users.findOne({ username: req.session.username })
console.log(user)
if (user){
console.log(user.likedposts)
if (!user.likedposts.includes(id)){
console.log("here")
req.article = await Article.findById(id)
req.article.pop += 1
let article = req.article
user.likedposts.push(id)
await user.save()
await article.save()
return "done"
}
else{
console.log("already liked this post")
return "already liked this post";
}
}
else{
console.log("sighn in");
return {test: "must sighn in to like posts"};
}
})
使用 res.send() 而不是 return 因为 return 不用于事件处理程序。
要完成 Express 请求处理程序,您必须发送某种 http 响应。通常的方法是使用 res.send(...)
或 res.json(...)
,但如果您没有数据要发送,您也可以只使用 res.sendStatus(xxx)
甚至 res.end()
.
Express 不会关注您从请求处理程序中 return
得到的内容,因此从请求处理程序返回一个值什么都不做——它被完全忽略了。相反,您必须显式调用上述方法之一来发送 http 响应。
如果您不通过在响应对象上调用这些类型的 Express 方法之一来发送 http 响应,那么客户端只是坐在那里等待响应返回到它的请求,它会等待一段时间直到最终它使请求超时。
我有一个功能设置,主要用于检查某人是否已登录以及他们是否将 1 添加到变量中。问题是当 运行 在诸如邮递员之类的应用程序中它会永远持续下去,而当在浏览器中 运行 它永远不会去.then.
Html
$('.fa-regular.fa-heart').click(function(){
$regular.toggleClass('hide');
$solid.toggleClass('hide');
$added.toggleClass('hide');
$noadded.toggleClass('hide');
console.log("running");
fetch("/articles/popplus/<%= article.id%>", {
method: 'POST',
mode: 'cors',
cache: 'default',
body: JSON.stringify(null)
}).then((data) => {
console.log("data")
console.log(data)
});
})
Node.js
router.post('/popplus/:id', async (req, res, next) => {
var id = req.params.id;
const user = await Users.findOne({ username: req.session.username })
console.log(user)
if (user){
console.log(user.likedposts)
if (!user.likedposts.includes(id)){
console.log("here")
req.article = await Article.findById(id)
req.article.pop += 1
let article = req.article
user.likedposts.push(id)
await user.save()
await article.save()
return "done"
}
else{
console.log("already liked this post")
return "already liked this post";
}
}
else{
console.log("sighn in");
return {test: "must sighn in to like posts"};
}
})
使用 res.send() 而不是 return 因为 return 不用于事件处理程序。
要完成 Express 请求处理程序,您必须发送某种 http 响应。通常的方法是使用 res.send(...)
或 res.json(...)
,但如果您没有数据要发送,您也可以只使用 res.sendStatus(xxx)
甚至 res.end()
.
Express 不会关注您从请求处理程序中 return
得到的内容,因此从请求处理程序返回一个值什么都不做——它被完全忽略了。相反,您必须显式调用上述方法之一来发送 http 响应。
如果您不通过在响应对象上调用这些类型的 Express 方法之一来发送 http 响应,那么客户端只是坐在那里等待响应返回到它的请求,它会等待一段时间直到最终它使请求超时。