I’m new to web development. Have a simple Node.js app running express and using handlebars: index.hbs, results.hbs.
index.hbs (simplified)
<div id="answer">
The answer:<span>answer="{{answer}}"></span>
</div>
results.hbs (simplified)
<div id="results">
You are {{result}}! The answer is:<span>answer="{{answer}}"></span>
</div>
server.js
app.get('/results', async function(req, res) {
const answer = req.body.answer;
res.render('results', {
answer: answer
});
});
client.js
function displayResults() {
var results = number1 + number2;
var result;
if (results == correctAnswer) {
result = "correct";
answer = results;
} else {
result = "incorrect";
answer = number1 + number2;
}
fetch('/results', {
method: 'POST',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(result, answer) //how to send the result, answer to results.hbs?
}).then(function (res) {
// redirect to new page?
}).catch(function (e) {
console.log(`Error: ${e}`)
});
}
I have a client JavaScript that asks the sum of two numbers.
Once the answer is retrieved it determines if the answer is correct. If it is it sends the results as "correct", otherwise "incorrect" and the answer.
I’ve tried using POST via the fetch method on app.post(‘/results’)… and app.get(‘/results’)… but I’m confused on which to use to pass the value to display the result and answer and redirect to the results.hbs.
Questions:
How do I get the value from the client JavaScript to the Node.js server and pass it to '/results.hbs? Do I use a POST or GET?
How do I redirect to the “results.hbs” page from the Node.js server?
Thanks for the help. I know these are pretty basic but I’m not finding the answers specific to my use case.