Home > front end >  Post function running forever in JS
Post function running forever in JS

Time:05-05

I have a function setup to basically check if someone is signed in and if they are adding 1 to a variable. The problem is when run in an application such as a postman it lasts forever, and when to run in the browser it never goes to .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"};
  }
})

CodePudding user response:

Use res.send() instead of return becasue return is not used for event handlers.

CodePudding user response:

To complete an Express request handler, you MUST send some sort of http response. The usual way to do that is with res.send(...) or res.json(...), but if you have no data to send, you can also just do res.sendStatus(xxx) or even just res.end().

Express does not pay any attention to what you return from your request handler so returning a value from the request handler does nothing at all - it is entirely ignored. Instead, you must explicitly call one of the above methods to send an http response.

If you don't send an http response by calling one of these type Express methods on the response object, then the client just sits there waiting for a response to come back to its request and it waits for awhile until eventually it times out the request.

  • Related