hussain hussain - 2 months ago 14
Javascript Question

How to create POST rest api using nodejs?

I have printed data from an AngularJS controller to factory so client side has data for API, but when I post data to server side it's printing undefined

req.body
. Any idea what is missing in the code below?

I have
body-parser
module added to app.js

angularJsFactory.js

angular.module('App').factory('LogsFactory', function($http) {
'use strict';
return {
addNewUser: function(user) {
console.log('user in factory', user);
return $http.post('/newUser', user);
}
}
});


Node-App.js

var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var jsonfile = require('jsonfile');
var async = require('async');
var server = require('http').createServer(app);
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser')
var io = require('./app/io').initialize(server);
app.use(cookieParser());
require('./app/serverfiles/components/auth')(app);

app.use(express.static(__dirname + "/public"));

app.post('/newUser',function(req,res){
console.log(req.body);
});

Answer Source

Don't forget to have your Express app actually use the body parser.

app.use(bodyParser());