0

I am kind of stuck, please help me.I am trying to save as JSON file from HTML form. I not getting how to move data from angularjs controller to nodejs. If I send data from controller to Nodejs, where I can use fs.write method to save form data as json. Here I am pasting codes. My HTML form file,

<div ng-controller="Ctrl" class="row">
            <form>
                <p>
                    <label for="Name"> Name :</label>
                    <input id="Name" type="text" name="Name" ng-model="store.name"/><br /><br />
                </p>
                <p>
                    <label for="age"> Age :</label>
                    <input id="age" type="text" name="age" ng-model="store.age"/><br /><br />
                </p><p>
                    <label for="sex"> Sex :</label>
                    <input id="sex" type="text" name="sex" ng-model="store.sex"/><br /><br />
                </p>
           <textarea>{{store | json}}</textarea><br />
           <input type="submit" class="btn btn-primary" ng-click="send()">

Here is my app.js file

var app = angular.module('app',['ui.router','ui.bootstrap','ngAnimate'])
.controller('Ctrl',function($scope,$http){      
      $scope.data = {}
      $scope.response = {}

    $scope.send = function(){

        var receiveddata = $scope.store;

        console.log(JSON.stringify(receiveddata));})

I am able to print(receiveddata) success fully on the console. And output is showing properly.

And Here Is my server.js file.

var express = require("express");
var http = require('http');
var path = require('path');
var bodyParser = require('body-parser');
var fs = require('fs');
var formidable = require("formidable");
var util = require('util');

var app = express();
app.set('views', __dirname + '/views');
app.set('view engine' , 'ejs');

app.use(bodyParser.urlencoded());

app.use(express.static(path.join(__dirname,'public')));

app.get('/',function(req,res){
res.render('index',{ title: 'StoreAsJson' });
});
var server = app.listen(8000,function(){
var port = server.address().port;
console.log("server is listening on port %s",port);
});

Any one please help me in solving this problem. I have got writing to JSON file code from this link. I

Community
  • 1
  • 1
naik3
  • 319
  • 2
  • 8
  • 22

1 Answers1

3

I'll try to show an example using MEAN stack.

App.js:

(function(){
    'use strict';
    angular.module('app', [ 'ui.router','ui.bootstrap','ngAnimate' ]);
})();

Controller.js:

angular
    .module('app')
    .controller('Ctrl', Ctrl);

function Ctrl($scope, $http) {

    $scope.send = function(){
       //Saving data into a single var -> JSON format
       var userData = {
                        name : store.name,
                        age  : store.age,
                        sex  : store.sex
        };

    // Calls Back-end api to save the new user
    $http.post('/users', userData)
        .success(function(data) {
            console.log('Successfully posted '+ data);
        })
        .error(function(data) {
            console.log('Error while posting: ' + data);
        });

    }
}

server.js:

// Dependencies
var express         = require('express');
var mongoose        = require('mongoose');
var port            = process.env.PORT || xxxx;
var bodyParser      = require('body-parser');
var app             = express();

// Sets the connection to MongoDB
mongoose.connect("mongodb://localhost/UserApp");

. . . . . .

// Routes
require('./app/routes.js')(app);

. . . . . .

Routes.js:

Here I'm using Mongoose and MongoDB to store data. Posting to /users. For istance, if you go to localhost:xxxx/users you should be able to see all your users using getUsers method.

/** Requiring Factories **/
var UserFactory = require('./factories/user.factory.js');

// Opens App Routes
module.exports = function(app) {

  /** Posting a new user**/
  app.post('/users', function(req, res) {
      //Calling postUser method from factory
      UserFactory.postUser(req).then( function (user) {
          console.log('Successfully posted '+ JSON.stringify(user));
          res.json(user);
      });
  });

  /** Getting all the Users**/
  app.get('/users', function(req, res) {
      UserFactory.getUsers().then( function (users) {
          return res.json(users);
      }, function (error) {
          res.json(error);
      });
  });

}

user.factory.js:

//Requiring Mongoose user schema
var Users = require('../models/user-model.js');

//Exposing getUsers and postUser to external calls
exports.getUsers = getUsers;
exports.postUser = postUser;

/** Gets all the users stored in the DB **/
function getUsers() {
    return new Promise( function (resolve, reject) {
        //Opens Mongoose Query
        var query = Users.find({});
        query.exec(function(err, users) {
            if (err){
                return reject(err);
            }
            // If no errors are found, it responds with a JSON of all users
            return resolve(users);
        });
    }, function (error){
        return reject(error);
    });
}

/** Posting a new users**/
function postUser(req) {
    return new Promise( function (resolve, reject) {
        // Creates a new user based on the Mongoose schema and the post body
        var newUser = new Users(req.body);
        // New Points is saved in the db.
        newUser.save(function(err) {
            if (err){
                reject(err);
            }
            // If no errors are found, it responds with a JSON of the new user
            resolve(req.body);
        });
    }, function (error){
        return reject(error);
    });
}

user-model.js:

//Pulls Mongoose dependency for creating schemas
var mongoose = require('mongoose');
var Schema   = mongoose.Schema;

// Creates a User Schema, it will automatically set an _id to a user
var users= new Schema({
                        name : {type : String},
                        age  : Number,
                        sex  : {type : String}
});

//Saves schema to DB
module.exports = mongoose.model('users', users);

If you take a look at how MongoDB and Mongoose work you should get it going easily.

You asked a very broad question, so this is not intended to be a precise answer.

PLUS

  • Avoid using names like Ctrl
  • Use this

html:

 send() -> myCtrl.send()
 store  -> myCtrl.store.name, myCtrl.store.age, myCtrl.store.sex

controller:

angular
.module('app')
.controller('myCtrl', myCtrl);

   function myCtrl($http) {

       var vm = this;

       vm.send = function(){
          //Saving data into a single var -> JSON format
          var userData = {
                           name : vm.store.name,
                           age  : vm.store.age,
                           sex  : vm.store.sex
           };

       // Calls Back-end api to save the new user
       $http.post('/users', userData)
           .success(function(data) {
               console.log('Successfully posted '+ data);
           })
           .error(function(data) {
               console.log('Error while posting: ' + data);
           });
       }
    }  

I hope I've been helpful.

AndreaM16
  • 3,917
  • 4
  • 35
  • 74
  • Thank you very much for the reply. I dont want to change my url, means if I go to **localhost:xxxx/users** I will get the JSON data, But I dont want to change my url. On the same page when I hit Submit, It should save form data to JSON file. – naik3 Aug 12 '16 at 12:31
  • Hi, ofc you do not need to change url. The example was meant to tell you that if you want to get your users, you just do a call `$http.get` to `/users`. So, if you need to show, for istance, user data fetched from there, you just do a call, save that call into a variable and calling it from html in the usual way. – AndreaM16 Aug 12 '16 at 12:34
  • Hi, Sorry I dont know how to do. Can you please share any code. Here in my above code **receiveddata** variable contain proper JSON data, I just need to send it to server(nodejs) and save as JSON file, when I press Submit button. Please help me to solve this. – naik3 Aug 12 '16 at 12:38
  • I already showed you how to post `JSON` data on the example code above and it also gets saved into a `JSON` format file trough `MongoDB`. For instance, if you take a look at the newly created DB, users collection, you'll have all users in `JSON` format. – AndreaM16 Aug 12 '16 at 12:45
  • 1
    Ok. I will go through it , and i will try it. Thank you very much. – naik3 Aug 12 '16 at 12:48
  • HI.. I tried, but still I am not getting any thing from controller to nodejs server. Here I have posted another question [similar] (http://stackoverflow.com/questions/38930973/sending-post-request-from-angularjs-to-nodejs) to this one. please help me to solve the problem. – naik3 Aug 13 '16 at 08:52