Create a form with GET and POST routes in Express.js (framework for nodejs) and a view in .hbs format. I can also guide you on how to submit the form via AJAX in Express.js. Here are the steps you can follow:
1. Create a new Express.js application by running the following command:
npx express-generator --view=hbs myapp
2. Navigate to the project directory and install the necessary dependencies by running the following command:
cd myapp
npm install
3. Create a new route in routes/index.js
file to handle GET and POST requests for the form:
const express = require('express');
const router = express.Router();
// GET route for displaying the form
router.get('/', function(req, res, next) {
res.render('form');
});
// POST route for submitting the form
router.post('/', function(req, res, next) {
const name = req.body.name;
const email = req.body.email;
// Process the form data here
res.send(`Name: ${name}, Email: ${email}`);
});
module.exports = router;
4. Create a new view file views/form.hbs
to display the form:
<form id="myform" action="/" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>
<button type="submit">Submit</button>
</form>
- Install and configure the
body-parser
package to handle form data:
npm install body-parser
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
// Body parser middleware
router.use(bodyParser.urlencoded({ extended: false }));
// GET route for displaying the form
router.get('/', function(req, res, next) {
res.render('form');
});
// POST route for submitting the form
router.post('/', function(req, res, next) {
const name = req.body.name;
const email = req.body.email;
// Process the form data here
res.send(`Name: ${name}, Email: ${email}`);
});
module.exports = router;
5. Add a JavaScript file public/javascripts/main.js
to handle form submission via AJAX:
$(function() {
$('#myform').submit(function(event) {
event.preventDefault();
var data = $(this).serialize();
$.ajax({
type: 'POST',
url: '/',
data: data,
success: function(response) {
alert(response);
}
});
});
});
6. Finally, update the app.js
file to use the routes and set the view engine to .hbs
:
const express = require('express');
const indexRouter = require('./routes/index');
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
// Routes
app.use('/', indexRouter);
module.exports = app;
That’s it! You can now run your Express.js application by running the following command:
npm start
You can access the form by navigating to
http://localhost:3000/
in your web browser.