I am fresher to using Angular js and node js. I am doing File Uploading process by angular and node js. I already create directives and services by watching some tutorial. But in services Form data is not posting on NodeJs server. Here is following code file by file:-
Here is my Directive :-
myApp.directive('fileModel', ['$parse', function ($parse) { return { restrict: 'A', link: function(scope, element, attrs) { var model = $parse(attrs.fileModel); var modelSetter = model.assign; element.bind('change', function(){ scope.$apply(function(){ modelSetter(scope, element[0].files[0]); }); }); } }; }]); Here is service file code :-
myApp.service('multipartForm', ['$http', function($http){ this.post = function(uploadUrl, data){ var fd = new FormData(); for(var key in data) fd.append(key,data[key]); console.log(fd); $http({ url: uploadUrl, method: 'POST', headers: { 'Content-Type': undefined }, transformRequest: angular.identity, data: JSON.stringify(fd) }). success(function(data) { console.log('success'); }). error(function(data, response) { console.log(response + " " + data); }); }; }]); This is my angularjs code where i defined all methods :-
var myApp = angular.module('myApp', []); myApp.controller('saveJsonDemo',['$http','$scope','multipartForm',function($http,$scope,multipartForm){ $scope.formData = {}; $scope.saveJson = function() { var uploadUrl = '/savedata'; console.log($scope.formData); multipartForm.post(uploadUrl, $scope.formData); }; }]); When i post data though this service to node js server, and i console.log req.body and rex.files is becomes blank. Where is the problem in my code. Here is my Node js server file (app.js)
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var path = require('path'); var http = require('http'); var fs = require('fs'); var multer = require('multer'); var done = false; // all environments app.use(multer({dest: './uploads/'})); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(express.static(path.join(__dirname, 'public'))); app.set('port', process.env.PORT || 3000); app.use(function(err, req, res, next){ app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json({limit: '50mb'})); console.log(err); }); app.post('/savedata', function(req,res){ console.log('Here'); console.log(req.body); var currentTime = Date.now(); /*fs.writeFile('./json/'+currentTime+'.json', JSON.stringify(req.body), function (err) { if (err) return console.log(err); else res.send(); }); */ }); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); }); On the above /savedata method req is coming blank. Where is the mistake in my code.