简体   繁体   中英

Cannot post data from Angular.js to Node.js

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.

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM