Reputation: 83
I am trying to do a simple POST call to a RESTful API that I created. I am using Angular for the client-side, nodejs for the server, and mongodb+express+multer for the database.
When testing the back-end using POSTman, the objects are created correctly, getting data from the req.body. In my Angular controller's createProject method, I am printing out my formData right before POSTing to the API. The form data looks correct. When the correct form data is POSTed to the working server, the req.body shows up empty.
Here is my relevant server code:
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);
Here is my relevant Angular code:
$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);
});
};
Here is my relevant HTML code:
<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>
The Question:
How does Angular pass data from the $scope.formData to the request, and why is it not compatible with my server configuration? I'm pretty sure it has to do with the content-type in my POST, and how that relates to multer.
Thanks for your time!
Upvotes: 5
Views: 2676
Reputation: 262
You can use body parser middleware
app.use(bodyParser());
Upvotes: 1