33 points

How to Save HTML Form Data in JSON - Express


Posted by @mishka #html #javascript #nodejs

Step 0: Create a HTML form. Mention the names of the JSON fields in the "name" attribute.

<form action="/new" method="post">
  <input name="title" type="text">
  <input name="description" type="text">
  <button type="submit">Submit Form</button>
content_copy Copy

Step 1: Create a new Model for the data you want to save in JSON.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

const postSchema = new Schema({
    title: { type: String , required: true},
    description: { type: String},

var Post = mongoose.model('Post', postSchema);
module.exports = Post;
content_copy Copy

Step 2: Install the body-parser package

$ npm install body-parser
content_copy Copy

Step 3: Create a POST method to handle the form.

var express = require('express');
var router = express.Router();
const Post = require('../models/post');

router.post('/new', (req, res) => {
    var post = new Post(req.body);

    post.save(function(err, user) {
        if(err) console.log(err);
        return res.send("Success! Your post has been saved.");
content_copy Copy