【问题标题】:Cannot post data from Angular.js to Node.js无法将数据从 Angular.js 发布到 Node.js
【发布时间】:2018-10-15 19:07:03
【问题描述】:

我正在使用 AngularJS 和 Node.js 创建一个 MEAN 堆栈应用程序。

这是我的 AngularJS 代码:

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

这是我的 Node.js 代码:

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 部分工作正常,在控制台中显示数据,发布数据并获得“发布成功”消息。

但在节点中,我无法获取 req.body 中发布的数据。

当我在浏览器“网络”中签入时,我得到了“create.html”内容。

需要别人的帮助。

【问题讨论】:

    标签: javascript angularjs node.js


    【解决方案1】:

    使用这个

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

    对于 get 你应该使用 req.params

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

    【讨论】:

    • 谢谢。但我仍然没有在我的 node.js 控制台中获取数据
    • 请显示您随请求发送的示例数据
    • 尝试添加 -headers: { 'Content-Type': 'application/json;字符集=utf-8' }
    猜你喜欢
    • 2018-06-22
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 2023-01-02
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    相关资源
    最近更新 更多