How to Save HTML Form Data in JSON - Express


Saved 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>

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;

Step 2: Install the body-parser package

$ npm install body-parser

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

var express = require('express');
var router = express.Router();
const Post = require('../models/post');'/new', (req, res) => {
    var post = new Post(req.body);, user) {
        if(err) console.log(err);
        return res.send("Success! Your post has been saved.");