Vinit Modi
Vinit Modi

Reputation: 11

How to display MongoDB data in html page

I'm working on a project where I need to display the user data into the HTML web-page. For that, I have already created the POST and GET methods for API. I don't know how do I display the data on the webpage.
PS: I'm not allowed to use frameworks like angular or react. I have to do it with MEN stack.

POST method:

router.post('/adduserdata', (req, res) => {
    bcrypt.hash(req.body.password, 10, (err, hash) => {
        if (err) {
            res.json({
                error: err
            });
        }
        else {
            const user = new userdata({
                name: req.body.name,
                email: req.body.email,
                password: hash,
                mobile_no: req.body.mobile_no,
                data_of_birth: req.body.data_of_birth
            })
            try {
                user.save()
                res.json({
                    message: "User Created.."
                });
            }
            catch (err) {
                res.send('Error');
            }
        }
    });
});

GET method:

router.get('/getuserdata', async (req, res) => {
    try {
        const user = await userdata.find().select("name email mobile_no data_of_birth")
        res.json(user)
    }
    catch (err) {
        res.send('Error ', err)
    }
});

Upvotes: 0

Views: 2055

Answers (2)

Aashish Thoutam
Aashish Thoutam

Reputation: 11

You need to have a placeholder for the user data in your HTML:

<h1 id="name"></h1>

Then in the javascript of the page you need to make a request to your /getuserdata endpoint and then modify the DOM with the result of the API call:

<script>
  fetch('http://example.com/getuserdata')
    .then(response => response.json())
    .then(user => {
       document.getElementById("name").innerHTML = user.name; 
    });
<script>

Upvotes: 1

Mars
Mars

Reputation: 98

You'll basically need to do some DOM handling and Ajax requests.

In pure JS:

const htmlElement = document.getElementById("YourElement");
const req = new XMLHttpRequest();
req.onreadystatechange = () => {
    if (req.readyState == 4 && req.status == 200) {
         const data = req.response;
         console.log(data) // Shows the returning data, that will probably be a JSON OBJECT.
         htmlElement.inneText = data.name;
    }
};
xhttp.open("GET", "/getuserdata");
xhttp.send();

Code BREAKDOWN:

htmlElement: creates a constant variable that contains a HTML element with the provided ID.
req: creates a HTTP request client.
The rest of the code is all about this two variables. The HTTP client called req sends a REQUEST to the server, checks if the request was loaded (readyState 4) and verify if the request was successful (HTTP status 200). If these conditions are met, then the program will create a variable with the DATA returned from the request and uses this data to fill the HTML webpage.

Ps: you could also use req.responseText to convert the json object directly to a DOMString.

Upvotes: 1

Related Questions