0

what I´m trying to do is the following I already set a fetch connection from client side JS to the server Node.JS when a person click on a button in HTML which triggers that in the server side looks for an element in the MongoDB database in it find´s it, but my question is how do I send that found element back to the client side JS.

Javascript Code:

var button = document.getElementById("1");

button.addEventListener("click", idss);


function idss() {
      var id = this.id;

    var data = {
    name : id 
}

fetch("/clicked", {
     method: 'POST',
     headers: {
     'Content-Type': 'application/json'
     }, 
     body: JSON.stringify(data)
})
   .then(function(response) {
      if(response.ok) {
        console.log('awesome');
        return;
      }
      throw new Error('Request failed.');
    })
    .catch(function(error) {
      console.log(error);
    }); 
}


NODE JS:

app.post("/clicked", (req, res) => {
    var pro = (req.body.name);
    Number(pro);
    Product.findOne({"id": pro}, function(err, foundLList) {
        if(err) {
            console.log(err);
        } else {
            console.log(foundLList); //THE ELEMENT IS FOUND
        }
    } 
  ); 
});

What I´m trying to do is to send the found element to Javascript so I can added to another variable.

2
  • in Node.js use res.send(data); to actually return something. As far as I know most of MongoDB function are async, so it's better to use async/await Commented Jul 20, 2019 at 19:21
  • You're using Express.js and this is covered in the basic Hello World example at the start of the documentation. Commented Jul 20, 2019 at 19:22

1 Answer 1

1

You have to use res object to send data back to client. Your node code will be:

app.post("/clicked", (req, res) => {
    var pro = (req.body.name);
    Number(pro);
    Product.findOne({
        "id": pro
    }, function(err, foundLList) {
        if (err) {
            console.log(err);
            return res.status(500).json({
                ok: false,
                error: err
            });
        } else {
            console.log(foundLList); //THE ELEMENT IS FOUND
            return res.status(200).json({
                ok: true,
                data: foundLList
            });

        }
    });
});

and on client side, you can read the data like this:

fetch("/clicked", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(function(response) {
        if (response.ok) {
            console.log('got data: ', response.data);
        }
        throw new Error('Request failed.');
    })
    .catch(function(error) {
        console.log(error);
    });
}
Sign up to request clarification or add additional context in comments.

4 Comments

I tried put I´m getting undefined in the undefined for response.data.
try converting response object to JSON. Add .then(response => response.json()) before the then we have
Thaks Mohammed I resolve it with this code .then(response => response.json()) .then(res => { if(res.ok) { console.log(res); }
glad it help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.