关于node.js:在Angular中发布时,Form Data是正确的,但是node中的req.body为空吗?

Form Data is correct when POSTing in Angular, but req.body is empty in node?

我正在尝试对我创建的RESTful API进行简单的POST调用。我在客户端使用Angular,在服务器上使用nodejs,在数据库中使用mongodb express multer。

使用POSTman测试后端时,将正确创建对象,并从req.body获取数据。在Angular控制器的createProject方法中,我正要在发布到API之前打印出formData。表单数据看起来正确。将正确的表单数据发布到工作服务器后,req.body将显示为空。

这是我相关的服务器代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
app.use(express.static(__dirname + '/public'));
app.use(multer({ dest: 'public/uploads/'}));

router.route('/projects')  // accessed at //localhost:8080/api/projects

.post(function(req, res) {
    console.log(req.body); // returns empty set
    var project = new Project();

    project.name = req.body.name;
    project.description = req.body.description;
    project.newComments = 0;
    project.newPosts = 0;
    //project.imageURL = req.body.imageURL;

    project.save(function(err) {
        if (err)
            res.send(err);

        Project.find(function(err, projects) {
            if (err) res.send(err);
            res.json(projects);
        });
    });
})

app.use('/api', router);

这是我相关的Angular代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
$scope.createProject = function() {
    console.log($scope.formData); // returns correct **{name:"adawda", description:"dawdaw"} **
    $http.post('/api/projects', $scope.formData)
        .success(function(projectData) {
            $scope.formData = {};
            $scope.imageURL ="";
            $scope.projects = projectData;
            console.log(projectData);
        })
        .error(function(projectData) {
            console.log('Error: ' + projectData);
        });
};

这是我相关的HTML代码:

1
2
3
<input type="text" placeholder="name of project" ng-model="formData.name" />
<input type="text" placeholder="description" ng-model="formData.description" />
<button type="submit" class="button" ng-click="createProject()">Create Project</button>

问题:

Angular如何将数据从$ scope.formData传递到请求,为什么它与我的服务器配置不兼容?我很确定这与我的POST中的内容类型以及与multer的关系有关。

感谢您的时间!


您可以使用正文解析器中间件

app.use(bodyParser());