I'm using node.js/express, and I've got a view with a form on it - that form POST's to a route, which then returns json.
I'd like to (to start with at least) send off my form, and have the data that's returned be shown underneath the form (on the same view).
What's the best way of doing this in the most 'express-y' way possible?
Ideally without a page refresh.
Ajax will do what I'm after - but is that a great way of doing it?
The bare minimum of what you're looking for would look something like this:
Client side
fetch('your_endpoint', {
method: 'POST',
body: JSON.stringify(formData),
}).then((response) => {
// success
return response.json();
})
.then((data) => {
// add data to DOM
})
.catch((error) => {
// failed to send
});
Server side using Expressjs
router.post('/your_endpoint', (req, res, next) => {
// process request
res.status(200).json({ "data": your_data });
});