【发布时间】:2015-12-07 17:36:05
【问题描述】:
我目前正在使用 Node/Express 和 Ionic/Angular 开发 MEAN 堆栈应用程序。我有一个页面,用户可以在其中编辑/删除特定对象的内容。删除功能有效,但是当我单击编辑并触发放置/更新功能时,它会清除除 id 号和 "__v": 0 之外的数据,而不是更新对象。
我已经使用 Postman 检查了服务器端 API,它可以使用正文内容类型 x-form-urlencoded 进行更新。我的预感是在客户端正确获取数据。任何帮助是极大的赞赏。
下面是我的 Ionic/Angular 控制器代码:
.controller('UpdateCtrl', function($stateParams, $rootScope, $scope, HomeFac) {
id = $stateParams.id;
$scope.location = {};
HomeFac.getLocation(id).success(function(data) {
$scope.location = data;
});
$scope.edit = function() {
meet = $scope.location;
location = angular.fromJson(meet);
console.log(location);
HomeFac.updateLocation(id, location)
.then(function(id, location)
{
console.log("good");
});
};
$scope.delete = function() {
HomeFac.deleteLocation(id);
};
});
服务器端:
exports.putLocation = function(req, res) {
// Use the Beer model to find a specific beer
Location.findById(req.params.location_id, function(err, location) {
// Update the existing location
location.name = req.body.name;
location.category = req.body.category;
location.latitude = req.body.latitude;
location.longitude = req.body.longitude;
// Save the beer and check for errors
location.save(function(err, location) {
if (err) {
res.send(err)
};
res.json(location);
});
});
};
HomeFac 更新功能
_LocationService.updateLocation = function(_id, location) {
return $http.put(urlBase + '/' + _id, location);
};
【问题讨论】:
-
您是否在中间件堆栈中启用了
bodyParser.json()? -
@PrashanthChandra。是的。在我的 server.js 上,我有 bodyParser.json() 并添加了 bodyParser.urlencoded({ extended: true })。
-
另外,在
exports.putLocation中,您只是在阅读req.params。如果您将 JSON 放入服务器,req.params将为空,数据将在req.body中。你必须考虑到这一点。 -
试试
if (req.body) location = req.body; else {location.name = req.params.name...} -
x-form-urlencoded发送数据时,数据在req.params.<property of object>,而application/json,数据在req.body
标签: javascript angularjs node.js ionic mean-stack