req.body空Node.js

时间:2016-11-08 09:10:19

标签: angularjs node.js express

这是我的角度控制器代码,我通过certificationid和userid删除用户的认证详细信息。

$scope.deleteCertification = function(CertificationId){
  var userName = $scope.userId;
  var certificationId = CertificationId;
  var deleteCertificationInfo = {'userName': userName, 'certificationId':certificationId};
  console.log('deleteCertificationInfo*******');
  console.log(deleteCertificationInfo);
  userProfileService.deleteUserCertificationInfo(deleteCertificationInfo).then (function(data){
   console.log($scope.Certification);
    console.log('Certification Deleted');
  })
}

userProfileData.deleteUserCertificationInfo = function (deleteCertificationInfo) {
  var deferred = $q.defer();
  $http.delete('/api/profileUpdate/deleteUserCertification', deleteCertificationInfo, {
  }).success(function(res){
    var deletedUserCertificationResult = res;
    deferred.resolve(deletedUserCertificationResult);
    $log.debug('response from certification API:['+JSON.stringify(deletedUserCertificationResult)+']');
  }).error(function(err){
    deferred.reject(err);
  });
  return deferred.promise;
};

用userProfileService编写,用于调用delete API。

但在我的节点控制器函数中,req.body为空。不确定它的去向。我在将数据发送到服务之前对其进行安慰。然后显示它。但为什么req.body变空了?

2 个答案:

答案 0 :(得分:1)

即使您没有发布应用的Express部分,但最好的猜测是您没有使用body-parserbody-parser是使用req.body时需要的Express中间件,在不将其添加到Express应用程序的情况下,您将无法解析任何传入的JSON或URL编码的请求正文。

const express = require('express');
const bodyParser = require('body-parser');
const port = process.env.PORT || 3000;

let app = express();

app.use(bodyParser.json()); // this will parse Content-Type: application/json 
app.use(bodyParser.urlencoded({ extended: true })); // this will parse Content-Type:  application/x-www-form-urlencoded

// Your routes go here

app.listen(port);

答案 1 :(得分:0)

尝试下面的代码,它对我有用,你应该在你的节点服务js文件中有这个代码

app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
    extended: true
}));