使用Angularjs和Nodejs从HTML表单另存为JSON文件

时间:2016-08-12 11:38:49

标签: html angularjs json node.js express

我有点卡住,请帮助我。我正在尝试从HTML表单保存为JSON文件。我没有得到如何将数据从angularjs控制器移动到nodejs。如果我将数据从控制器发送到Nodejs,我可以使用 fs.write 方法将表单数据保存为json。我在这里粘贴代码。 我的HTML表单文件

<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()">

这是我的app.js文件

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));})

我能够在控制台上完全打印(receiveddata)成功。输出显示正常。

这是我的server.js文件。

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);
});

任何人请帮助我解决这个问题。我已经从this链接写入了JSON文件代码。我

1 个答案:

答案 0 :(得分:3)

我将尝试使用 MEAN 堆栈显示示例。

<强> 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:

我在这里使用MongooseMongoDB来存储数据。发布到/users。如果您转到localhost:xxxx/users,您应该可以使用getUsers方法查看所有用户。

/** 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);
    });
}

用户-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);

如果你看一下MongoDBMongoose的工作方式,你应该轻松​​搞定。

你提出了一个非常广泛的问题,所以这不是一个准确的答案。

<强> PLUS

  • 避免使用Ctrl
  • 等名称
  • 使用this

<强> HTML:

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

<强>控制器:

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);
           });
       }
    }  

我希望我一直很有帮助。