req.body在快递4.13.1中未定义

时间:2016-10-23 19:09:21

标签: angularjs node.js express body-parser

我有问题,我不知道问题。请帮我找到解决方案。

在Angular视图中我有:

<form ng-submit="submit()">
<input ng-model="stickie_text" type="text" id="sticky_content" />
<button type="submit" id="add_sticky" value="add a new stickie!">new sticky</button>

在客户端(AngularJS)我有这个控制器:

dcuApp.controller('rankingController', ['$scope', '$http',function($scope, $http) {$scope.submit = function(){
// console.log("holaaaa");
console.log($scope.stickie_text);
$http.get('/api/get-ranking',{"valor":$scope.stickie_text}).then(function(response) {
        $scope.data = response.data;
        console.log("RANKING: "+$scope.data);
    },
    function(response) {
        console.debug('Error:' + response);
    });
 };
 }]);

在服务器端(Express 4.13.1),我有:

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var db = require('../model/db');
var model = require('../model/model');
var fs = require('fs');
var async = require('async');
var bodyParser = require('body-parser');
var methodOverride = require('method-override'); //used to manipulate POST

router.use(bodyParser.urlencoded({ extended: true }))
router.use(methodOverride(function(req, res){
      if (req.body && typeof req.body === 'object' && '_method' in req.body) {
        // look in urlencoded POST bodies and delete it
        var method = req.body._method
        delete req.body._method
        return method
      }
}));

router.get('/api/get-ranking',function(req,res,next){
  console.log(req.body.valor);
});

问题是req.body.valor是UNDEFINED。

我知道还有其他与此问题相关的帖子,但尚未设法修复它。

请,我需要帮助才能进入服务器端,不同的req.body.valor到undefined

感谢!!! :)

1 个答案:

答案 0 :(得分:0)

您正在尝试执行GET请求并发送data。您需要使用POST请求来实现您的目标。您无法在GET请求中发送数据。

您需要将当前的GET方法更改为POST

替换:

router.get('/api/get-ranking',function(req,res,next){
  console.log(req.body.valor);
});

<强>与

router.post('/api/get-ranking',function(req,res,next){
  console.log(req.body.valor);
});

替换:

$http.get('/api/get-ranking',{"valor":$scope.stickie_text})

<强>与

$http.post('/api/get-ranking',{"valor":$scope.stickie_text})

希望这有帮助。