Home > OS >  Render express response in html element using fetch
Render express response in html element using fetch

Time:11-08

I'm currently working on a little node/express project that displays the bcyrpt hashed value of a users input. I can get the hashed value to display in the servers console.log, but I'm having a hard time injecting the value into the frontend's div that I designated for the results.

index.html

    <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bcrypt Input Page</title>
</head>

<body>
    <form action="/submit-form" method="POST">

        <label for="string"><b>String Input:</b></label>
        <br>
        <input type="text" name="string" required size="40" id="string">
        <input type="submit" value="Hash/Salt it!" id="submit-button">
    </form>

    <section id="responseArea">

    </section>
    <script src="/script.js"></script>
</body>

</html>

app.js

var express = require('express');
var app = express()
const path = require('path')
const { hashesString, passwordCheck } = require('./bcryptUtil');

app.use(express.urlencoded({
    extended: true
}))

app.use(express.static(path.join(__dirname, 'public')))

app.post('/submit-form', (req, res) => {
    const userInput = req.body.string;
    hashesString(userInput)
        .then((output) => {
            console.log(output);
            res.send(JSON.stringify(output))


        })
        .catch(err => console.log(err))
})


app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname, '/index.html'));
    //line 10 suffices, you don't need the next line
    //res.sendFile(path.join(__dirname, './public/script.js'))
})



app.listen(3003);

script.js

const area = document.getElementById("responseArea")

//area.innerHTML = `<h1> Hello World! </h1>`;

const button = document.getElementById("submit-button");

button.addEventListener("click", launchAjax);

/* const launchAjax = (formData) => {
    fetch("/submit-form", {
            method: "POST",
            body: JSON.stringify(formData)
        })
        .then(response => response.json())
        .then(responseJSON => {
            area.innerText = responseJSON;
        })
} */

const launchAjax = fetch('/submit-form')
    .then((res) => res)
    .then((data) => {
        area.textContent = data;
    })

So my question is, how do I use fetch to receive the response sent by the post request from the server and render it in the section element with the id of "responseArea" in the index.html file?

Also, there's a separate file with the bcrypt business logic, but I'm not including it because I don't think it's needed and it would just add clutter. If you do find you need it, feel free to ask though.

CodePudding user response:

Id try this

const launchAjax = () => {
   fetch('/submit-form',
        {method: 'POST'})
        .then(res => res.text())
        .then((data) => {
            area.textContent = data;
    })
}

CodePudding user response:

You can use JQuery to create a POST request like this

$.ajax({
  type: "POST",
  url: `/route`,
  data: { /* as an object */ },

  success: function (data) {
    console.log(data);
  },

  error: function (data) {
    console.error(data);
  },
});

<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>

Add this tag to use JQuery and after this line, reference the file where you are adding the previous code

This is not a very standard approach but it'll work properly.

NOTE: The script tag for JQuery might be old, so if you face a problem I suggest getting access to the latest JQuery URL

  • Related