POST Data with Server Action
Showcase how to handle POST requests using a server action to save submitted form data to a database.
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
// Connect to MongoDB database
mongoose.connect('YOUR_DATABASE_CONNECTION_URL');
// Define a Schema for the data
const DataSchema = new mongoose.Schema({
key: String,
value: String
});
// Create a Model based on the schema
const DataModel = mongoose.model('Data', DataSchema);
// Initialize express app
const app = express();
// Middleware to parse JSON bodies
app.use(bodyParser.json());
// POST endpoint to handle form submission
app.post('/submit-form', async (req, res) => {
try {
const { key, value } = req.body;
const newData = new DataModel({ key, value });
await newData.save();
res.status(201).send('Data saved');
} catch (error) {
res.status(500).send('Error saving data');
}
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
This piece of code creates an Express.js server with a POST endpoint '/submit-form'. It uses the Mongoose library to interact with a MongoDB database. It defines a Mongoose Schema and Model for the incoming data, adds bodyParser middleware to parse JSON request bodies, and listens for POST requests to save the form data to the database. Replace 'YOUR_DATABASE_CONNECTION_URL' with your actual MongoDB connection string.