数据不会在角度和节点js中的多部分表单数据中发布

数据不会在角度和节点js中的多部分表单数据中发布

本文介绍了数据不会在角度和节点js中的多部分表单数据中发布(使用角度和节点js上传文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我更加喜欢使用Angular js和node js。我正在做文件上传过程中的角度和节点js。我已经通过观看一些教程创建指令和服务。但是在服务中,表单数据不会在NodeJs服务器上发布。这里是以下代码文件的文件:

这是我的指令:
$ b $ pre $ code> myApp.directive('fileModel',['$ parse',function($ parse){
return {
restrict:'A',
link:function(scope,元素,attrs){
var model = $ parse(attrs.fileModel);
var modelSetter = model.assign;
$ b element.bind('change',function() {
scope。$ apply(function(){
modelSetter(scope,element [0] .files [0]);
});
});
}
};
}]);

以下是服务档案代码: - $ /

<$ ($ http $)$ $ b $ 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);
});
};
}]) ;

这是我的angularjs代码,我定义了所有的方法: -

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

}]);

当我通过这个服务发布数据给js服务器,而我console.log req.body和rex.files变成空白。我的代码中的问题在哪里?这里是我的节点js服务器文件(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;

//所有环境
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);
$ b app.use(function(err,req,res,next){
app.use(bodyParser.urlencoded({extended:true}));
app.use (bodyParser.json({limit:'50mb'}));
console.log(err);
});
$ b 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();
}); * /
});

$ b http.createServer(app).listen(app.get('port'),function(){
console.log('Express server listening on port'+ app.get('port'));
});

在上面的/ savedata方法中,req是空白的。

解决方案




http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js>



 < div ng-controller =myCtrl> 
< input type =filefile-model = myFile/>
<按钮ng-click =uploadFile()>上传我< / button>
< / div>

< script> ;
var myApp = angular.module('myApp',[]);
$ b $ myApp.directive('fileModel',['$ parse',function($ parse){
返回{
restrict:'A',
link:function(scope,element,attrs){
var model = $ parse(attrs.fileModel);
var modelSetter = model.assign;

element.bind('change',function(){$ b $ scope。$ apply(function(){
modelSetter(scope,element [0] .files [0]);
});
});
}
};
}]);
$ b myApp.service('fileUpload',['$ http',function($ http){
this.uploadFileToUrl = function(file,uploadUrl){
var fd = new FormData();
fd.append('file',file);

$ http.post(uploadUrl,fd,{
transformRequest:angular.identity,
标题:{'Content-Type':undefined}
})
$ b $ .success(函数(){
})

.error (function(){
});
}
}]);
$ b myApp.controller('myCtrl',['$ scope','fileUpload',function($ scope,fileUpload){
$ scope.uploadFile = function(){$ b $ (文件);
console.dir(文件);

var uploadUrl = / fileUpload;
fileUpload.uploadFileToUrl(file,uploadUrl);
};
}]);

< / script>






粘贴和更改您的api路径所需的角度服务调用控制器,然后它将工作:)


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.

解决方案

http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">

  <div ng-controller = "myCtrl">
     <input type = "file" file-model = "myFile"/>
     <button ng-click = "uploadFile()">upload me</button>
  </div>

  <script>
     var myApp = angular.module('myApp', []);

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

     myApp.service('fileUpload', ['$http', function ($http) {
        this.uploadFileToUrl = function(file, uploadUrl){
           var fd = new FormData();
           fd.append('file', file);

           $http.post(uploadUrl, fd, {
              transformRequest: angular.identity,
              headers: {'Content-Type': undefined}
           })

           .success(function(){
           })

           .error(function(){
           });
        }
     }]);

     myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
        $scope.uploadFile = function(){
           var file = $scope.myFile;

           console.log('file is ' );
           console.dir(file);

           var uploadUrl = "/fileUpload";
           fileUpload.uploadFileToUrl(file, uploadUrl);
        };
     }]);

  </script>

simply copy paste and change your api path in url required for angular service calling from controller then it will work :)

这篇关于数据不会在角度和节点js中的多部分表单数据中发布(使用角度和节点js上传文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 05:30