Я смогу:
Проблема: - Из службы я не могу получить доступ к своим данным в файле 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 ???**
})
Я новичок, поэтому, если требуются какие-либо изменения, пожалуйста, помогите мне.
Добавить body-parser на ваш server.js
var express = require('express'),
var app = express();
**var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json**
Затем вы можете использовать
req.body
для доступа к данным.
Попробуйте обновить код, как показано ниже.
Шаг 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;
}
}]);
customersService.postArticle($scope.list) .success(function() { console.log('post promise success!') }) .error(function(data, status, headers, config) { })
вкл. успех, успех обещания должен быть напечатан также. Почему это не печать?
customersService.postArticle($scope.list) .success(function() { console.log('post promise success!') }) .error(function(data, status, headers, config) { })
вкл. успех, успех обещания должен быть напечатан также. Почему это не печать?