Home > Back-end >  Display NodeJS Query result on webpage
Display NodeJS Query result on webpage

Time:01-22

I have a basic web application where users can upload pictures. I can list the URL-s of these pictures, but I can't figure out how can I display them on the page. Currently I am using a form to perform a get request because other methods did not work for me.

Server side:

router.get('/pictures', async (req, res) => {
  try {
    let user = await User.find({ 
      name: req.query.name
    });
    let result = []
    user.map(user => {
      result.push(user.avatar)
    })
    res.json(result)
  } catch (error) {
    console.log(error)
  }
})

Client side:

  <form action="/pictures" method="get">
    <input type="text" name="name">
    <input type="submit" value="Get Images" name="submit">
  </form>

This is what I get back:

[
"https://res.cloudinary.com/fidohuncloud/image/upload/v1642794180/eyrfrf8orusaz2bnq7pj.jpg",
"https://res.cloudinary.com/fidohuncloud/image/upload/v1642795673/rrqsddzbjwtfkrm1vbco.jpg"
]

CodePudding user response:

Its been a while when I worked last on the Forms submissions. Either you can use some JS Frameworks like React or Angular to do it very quickly. Or if you want to manipulate DOM, then you can just add it on the fly.

const images_from_client = [
  "https://res.cloudinary.com/fidohuncloud/image/upload/v1642794180/eyrfrf8orusaz2bnq7pj.jpg",
  "https://res.cloudinary.com/fidohuncloud/image/upload/v1642795673/rrqsddzbjwtfkrm1vbco.jpg"
];

images_from_client.forEach((img) => {
  const i_tag = document.createElement("img");
  i_tag.src = img;
  document.getElementById("app").appendChild(i_tag);
});
<!DOCTYPE html>
<html>

<head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
</head>

<body>
    <div id="app"></div>
</body>

</html>

CodePudding user response:

If you'd like to use vanilla javascript, it's possible by overriding the default form behavior.

<!DOCTYPE html>
<html>

<head>
    <title>Form submission</title>
    <meta charset="UTF-8" />
</head>

<body>

  <form id="image-form">
    <input type="text" name="name">
    <input type="submit" value="Get Images" name="submit">
  </form>
  <div ></div>
</body>
</html>

And your javascript can use the Fetch API to send a GET request to the backend server and append images into your HTML.

 document.getElementById("image-form").addEventListener("submit", function(e) {
    e.preventDefault();

    fetch("/pictures")
    .then(data => data.json())
    .then(data => {
      data.forEach(function(image) {
        let img = document.createElement("img");
        img.src = image;
        document.querySelector(".images").appendChild(img);
      });
    });
  });

  •  Tags:  
  • Related