我正在使用如下角色$ http发布请求向服务器提交表单
$scope.fileUp = function(){
var formda = new FormData();
for(var key in $scope.formval)
{
console.log(key, $scope.formval[key]);
formda.append(key, $scope.formval[key])
}
$http.post("/upload",formda, {
transformRequest : angular.indentity,
header : {'Content-Type' : undefined }
}).success(function(data){
console.log(data)
})
}
在我的节点服务器上,代码如下所示
var express = require("express");
var bodyParser = require("body-Parser");
var multer = require("multer");
var methodOverride = require('method-override');
var session = require('express-session');
var app = express();
app.use(express.static(__dirname + "/public"));
app.use(methodOverride());
app.use(session({ resave: true, saveUninitialized: true, secret: 'uwotm8' }));
app.use(bodyParser.raw({limit: '150mb'}));
app.use(bodyParser.urlencoded({limit: '150mb', extended: true}));
app.use(multer({dest : __dirname + '/public/Epub/'}))
app.post("/upload",function(request,response){
console.log(request.body)
console.log(request.files)
response.json({name : "a"});
})
app.listen(8080);
console.log("server running");
请求和响应很有效。我收到response.json({name:" a"});对于成功后邮政方法的要求。
问题出在节点服务器console.log(request.body)上, console.log(request.files)返回空{}。如何在邮寄请求中接收表单数据。
我在这里做错了。我是节点js的新手......
答案 0 :(得分:0)
试试这个:
$scope.fileUp = function(){
var formda = new FormData();
for(var key in $scope.formval)
{
console.log(key, $scope.formval[key]);
formda.append(key, $scope.formval[key]);
}
$http.post({
method: 'POST',
url: '/upload',
headers: {
'Content-Type':'application/json'
},
data: formda
}).success(function(data){
console.log(data);
});
}
通过添加app.use(bodyParser.json())来更改nodejs代码:
var express = require("express");
var bodyParser = require("body-Parser");
var multer = require("multer");
var methodOverride = require('method-override');
var session = require('express-session');
var app = express();
app.use(express.static(__dirname + "/public"));
app.use(methodOverride());
app.use(session({ resave: true, saveUninitialized: true, secret: 'uwotm8' }));
app.use(bodyParser.raw({limit: '150mb'}));
app.use(bodyParser.urlencoded({limit: '150mb', extended: true}));
app.use(bodyParser.json());
app.use(multer({dest : __dirname + '/public/Epub/'}))
app.post("/upload",function(request,response){
console.log(request.body);
console.log(request.files);
response.json({name : "a"});
})
app.listen(8080);
console.log("server running");
同时尽量避免语法错误,您的代码中缺少少量分号。
答案 1 :(得分:0)
$ http post方法然后使用函数而不是成功。并在对其进行字符串化后发送数据。
$http({
url:'/upload',
method: 'POST',
data: JSON.stringify({ userName: user})
}).then(function (res) {
$log.log(res.data);
$log.log(res.data.userFirstName);
});
答案 2 :(得分:-1)
node.js以 JSON 格式接收数据。在您的angularjs代码中,您直接发送 formda 对象。您应该在 JSON 中发送此包裹对象。例如:
var data = {"formdakey":formda}
现在,你应该发送数据对象到nodejs,在nodejs中你可以使用下面的代码片段检索formda的值:
var formdaval = req.body.formdakey;
尝试此操作并举报以防您仍然遇到问题。