I am not able to return JSON resposne back to a handlebars web form. I have a index.js file in a Node Application as shown:
const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');
var exphbs = require('express-handlebars')
const app = express()
app.use(express.json());
app.engine('handlebars', exphbs.engine());
app.set('view engine', 'handlebars');
const url = 'https://www.somedomain.com/api/someapi';
app.get('/', async (req, res) => {
res.render('form1');
});
app.post("/submit", async (req,res) => {
try {
const data = req.body;
const response = await axios.post(url, data);
result = response.data.result
if (result === "Ok") {
messages = "The input is ok.";
} else if (result === "not ok") {
messages ="The input is not ok.";
} else {
messages = "Unknown result.";
}
console.log(messages)
res.render('form1',{messages});
} catch (error) {
res.status(500).send('An error occurred while calling the API.');
}
})
And I also have a handlebars form called form1.handlebars as shown
<h1>Submit Your Information</h1>
<form id="dataForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age" required><br><br>
<label for="gender">Gender:</label>
<input type="text" id="gender" name="gender" required><br><br>
<label for="is_active">Is Active:</label>
<input type="checkbox" id="is_active" name="is_active"><br><br>
<button type="submit">Submit</button>
</form>
<h1>{{messages}}</h1>
<script>
document.getElementById('dataForm').addEventListener('submit', function(event) {
event.preventDefault();
const formData = {
data: {
id1: document.getElementById('name').value,
id2: document.getElementById('email').value,
id3: document.getElementById('age').value,
id4: document.getElementById('gender').value,
id5: document.getElementById('is_active').checked
}
};
fetch('/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
});
</script>
I am not able to return the result back to the web form even though when the console.log(messages) show the result.
What should I do to get the response back to the handlebars web form? Thanks
2