簡體   English   中英

AngularJS:無法從$ http.post()接收數據

[英]AngularJS: Unable to receive data from $http.post()

我能夠:

  • 使用ng-model和ng-submit指令將HTML文本框中的文本數據發送到Controller。
  • 將此數據從控制器發送到服務。

問題: -無法通過Service訪問Server.js文件中的數據,因此無法將數據插入MySQL表。

我的AngularJS服務使用內置的angularJS $ http服務發布數據。

我剛開始學習AngularJS,就遇到了這個問題。

為了方便起見,我已在適當的地方發表了評論。

HTML表單代碼:

<form class="form-horizontal"  ng-submit="submit()">

            <label class="control-label col-sm-2" for="id">ID:</label>
            <input type="text" class="form-control" id="id" placeholder="Enter ID" ng-model="text1">

            <label class="control-label col-sm-2" for="title">Title:</label>
            <input type="text" class="form-control" id="title" placeholder="Enter Title" ng-model="text2">

控制器代碼:

    (function() {
        var newArticleController = function ($scope, customersService, appSettings) {   
                $scope.list = []; // will pass this list
 //init function: customerService is a Service

                function init() {
                    customersService.postArticle($scope.list)
                        .success(function() {
                                console.log('post promise success!') //This is not printing!!!!!
                        })
                        .error(function(data, status, headers, config) {
                        })
                    }
    //on submit: init() is called
                $scope.submit = function() {
                    if ($scope.text1 && $scope.text2) {
                        $scope.list.push(this.text1)
                        $scope.list.push(this.text2)
                        init()
                        } } };

        angular.module('customersApp')
          .controller('newArticleController', newArticleController);
    }());

AngularJS 服務代碼:

(function(){ 
    var customersService = function($http) {
        this.postArticle = function(dataRcvd) {
            console.log('service called');
            console.log(dataRcvd); //This is printing

            return $http.post('/newArticle', JSON.stringify(dataRcvd))
        }

    }
    angular.module('customersApp').service('customersService', customersService);
}())

Server.js (問題在此部分)

 var express = require('express'),
 var app = express();

    var knex = require('knex')({
        //...
    });
    app.use(express.static(__dirname + '/'));

    app.post('/newArticle', function(req, res) {
            console.log('reached here: server.js')  //This is printing 

            ---> **//HOW TO ACCESS 'dataRcvd' here ???**    
    })

我是新手,所以如果需要任何修改,請幫幫我。

嘗試如下更新代碼。

步驟1-首先添加“ body-parser”。

var bodyParser = require('body-parser');

第2步,並將中間件作為

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

步驟3-嘗試按以下方式訪問數據。

app.post('/newArticle', function(req, res) {
        console.log('reached here: server.js')  //This is printing 

        ---> **//HOW TO ACCESS 'dataRcvd' here ???**  
          console.log(req.body);

          res.end();    
})

因此,要兌現承諾,請按如下所示更新您的服務代碼。

 angular.module('customersApp').service('customersService', ['$http', '$q', function ($http, $q) {


    this.postArticle = function(dataRcvd) {
       var deferred = $q.defer();
       console.log('service called');
       console.log(dataRcvd); //This is printing
      $http({
       method: 'POST',
       url: '/newArticle',
        headers: {'Content-Type': 'application/json'},
       data: JSON.stringify(dataRcvd)
       }).success(function (data) {
          deferred.resolve(data);
       }).error(function (msg) {
          deferred.reject(msg);
       });
       return deferred.promise;
    }
 }]);

將正文解析器添加到您的server.js

var express = require('express'),
var app = express();

**var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json**

那你可以用

req.body

訪問數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM