Simple Express app that serves as a landing page with a form that allows users to submit their email addresses:
Copy codeconst express = require('express');
const app = express();
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;
// serve static files from the 'public' directory
app.use(express.static('public'));
// use body-parser to parse form data
app.use(bodyParser.urlencoded({ extended: true }));
// connect to the database
MongoClient.connect('mongodb://localhost:27017/mydatabase', (err, client) => {
if (err) {
console.log(err);
return;
}
console.log('Connected to database');
const db = client.db('mydatabase');
// set the view engine to ejs
app.set('view engine', 'ejs');
// render the landing page with the email form
app.get('/', (req, res) => {
res.render('index.ejs');
});
// handle form submission
app.post('/submit-email', (req, res) => {
const email = req.body.email;
console.log(`Received email: ${email}`);
// save the email to the database
db.collection('emails').insertOne({
email: email
}, (err, result) => {
if (err) {
console.log(err);
return;
}
console.log(`Saved email to database: ${email}`);
// redirect back to the landing page
res.redirect('/');
});
});
// start the server
app.listen(3000, () => {
console.log('Express app listening on port 3000');
});
});
To run this app, you must have installed Node.js, Express, body-parser, and MongoDB. Here's how you can install and run the app:
Make sure you have Node.js installed. If you don't have it installed, you can download the latest version from the official website: nodejs.org
Install MongoDB by following the instructions on the official website: docs.mongodb.com/manual/installation
Please create a new directory for your app and navigate to it in your terminal.
Run the following command to install Express and body-parser:
npm install express body-parser
Create a file called
app.js
in your directory and paste the code above into it.Create a directory called
public
and create a file calledindex.ejs
inside it. This file will contain the HTML for your landing page. Here's an example of what it could look like:
Copy code<!DOCTYPE html>
<html>
<head>
<title>Landing Page</title>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<h1>Welcome to our landing page</h1>
<form action="/submit-email" method="