How to render a loading page in a website while waiting for response

Viewed 866

I am currently building a web application using NodeJS and express. One feature of this application is to have a user upload images (which is then stored in a cloud server).
However, i find that this sometimes takes a lot of time and the server is waiting for a response. I tried adding a loading screen but that is only triggered when the website is loading, and not while it's waiting for a response (as in the above case). Here is the code for the loading screen

<div class="loader">
   <img src="/loading.gif" alt="Loading..." />
</div>

<script>
        window.addEventListener("load", function () {
        const loader = document.querySelector(".loader");
        loader.className += " hidden"; // class "loader hidden"
    });
</script>

There's some CSS involved which I'm not posting here, but this loading screen works fine.
Here is the part that handles the request.

router.post('/campgrounds',middleware.isLoggedIn, upload ,(req,res)=>{
    //BELOW PROCESS TAKES LOT OF TIME
    //ADD A LOADING SCREEN HERE TILL IT REACHES "SUCCESS"
    cloudinary.uploader.upload(req.file.path, function(error, result) {
    if(error) {
        req.flash('error', err.message)
        return res.redirect('back')
    }
    // add cloudinary url for the image to the campground object under image property
    req.body.campground.image = result.secure_url;
    req.body.campground.imageId = result.public_id;
    req.body.campground.author = {
        id: req.user._id,
        username: req.user.username
    }
    Campground.create(req.body.campground, function(err, campground) {
        if (err) {
        req.flash('error', err.message);
        return res.redirect('back');
        }
        console.log("SUCCESS")
        req.flash("success","Successfully posted")
        res.redirect('/campgrounds/' + campground.id);
    });
    });
})

As mentioned, i want to render a loading screen while it uploads. How do i do this while the client is waiting for a response?
Any help is much appreciated

1 Answers

I assume you know when your website is making a request.

In the function that handles creating the request, you can add a loading icon to the html somewhere, and then you can listen for response.on('end') or something similar.

Once the response is received, you can get rid of the loader, and replace it with the data.

Related