12 works

How to Save HTML Form Data in JSON - Express


dashboard+ Project

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>
 
</form>
content_copyCopy to Clipboard

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_copyCopy to Clipboard

Step 2: Install the body-parser package

$ npm install body-parser
content_copyCopy to Clipboard

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_copyCopy to Clipboard

Code snippet source:

,

>> Browse more code snippets

more_vert