0

I am creating a MEAN stack application using AngularJS and Node.js.

Here is my AngularJS code:

app.js:

    var app = angular.module('crudApp', ['ngRoute']);

    app.config(['$routeProvider','$locationProvider', 
        function($routeProvider,$locationProvider){
            $routeProvider
                .when('/employees/create', {
                    templateUrl : 'create.html',
                    controller  : 'EmployeeController'
                }).when('/nothing', {
                    templateUrl : 'main.html',
                    controller  : 'mainController'
                });
            $locationProvider.html5Mode(true);
    }]);

    app.controller('EmployeeController',function($scope,$http) {
        $scope.save = function(data) {
            $scope.data = JSON.stringify(data);
            console.log(data);
            $http.post("http://localhost:8080/employees/create-employee",$scope.data).then(function(response) {
                console.log("posted successfully");
            });
        };
    });

Here is my Node.js code:

server.js:

var express  = require('express');
var app      = express();
var cors     = require('cors');
var bodyParser = require('body-parser');
app.use(cors());

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

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
   extended: true
}));

app.use('*',function(req, res) {
    res.sendFile(__dirname + '/angularjs/public/index.html');
});

require('./node/routes')(app);

app.listen(8080);

routes.js:

module.exports = function(app) {
  app.get('/employees/create-employee',function(req,res) {
      console.log(req.body);
});

Angular part is working fine, displays data in console, posting the data and getting "posted successfully" message.

But in node, I am unable to get the posted data in req.body.

I am getting the "create.html" content when I checked in browser "network".

Need someone's help.

1 Answer 1

1

Use this

module.exports = function(app) {
  app.post('/employees/create-employee',function(req,res) {
      console.log(req.body);
});

And for get you should use req.params

module.exports = function(app) {
  app.get('/employees/create-employee',function(req,res) {
      console.log(req.params);
});
Sign up to request clarification or add additional context in comments.

3 Comments

thanks. but still i am not getting the data in my node.js console
pls show the sample data you are sending with the request
try adding -headers: { 'Content-Type': 'application/json; charset=utf-8' }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.