I need to send data from the front-end of my Express application, to the back-end, and then render a page using EJS which needs to display that data.
The problem is the app.post()
method, and subsequently the res.render()
function do not seem to execute fully or properly when I make a "manual" POST request via $.post
or $.ajax
Suppose I make this POST request via JQuery
$.post("/test", {
testData: 'Some test data.'
});
Or this POST request via AJAX
$.ajax({
type: 'POST',
data: {
testData: 'Some test data here.'
}),
url: '/test',
})
And I configure my app.post() method to handle that route in Express
app.post('/test', function(req, res) {
res.render('./test.ejs', {
testMessage: req.body.testData
});
});
The variable testData will be sent through and received by the app.post() method. So say if I did this: console.log(req.body.testData)
, the output would be Some test data
, so there's no problem there.
The problem is with the res.render()
function, it simply doesn't work at all if the POST
request is made through $.post
or via AJAX$.ajax
. The res.render() function does not execute or render the page through POST requests made through $.post
or $.ajax
.
Strangely, if did the same POST
request via a form (which I do not want to do in my application because the POST
request is not supposed to send data received from an input), with the EXACT same app.post()
route handler in Express it works perfectly.
For example, using a form like the one below works and allows res.render()
to display the page, whereas the $.post()
and $.ajax
methods do not. Why is that so?
<form id="form-test" role="form" action="/test" method="post">
<input type="text" name="testData" placeholder="Test Data Goes Here" class="form-control" required>
<button class="btn" type="submit">Submit</button>
</form>
I've found another question on StackOverflow extremely similar to mine, but with no clear workaround other than the form option (which I cannot use) : Express.js Won't Render in Post Action
Any suggestions?