如何从Nodejs中的帖子请求中获取正文?

时间:2016-03-07 20:20:27

标签: javascript angularjs node.js post express

我使用post方法将数据id发送到我的节点服务器。但是req.body在我的节点文件中未定义

我的index.html如下所示:

<html ng-app="IMDBApp">
<body>
    <div ng-controller="testController as movieFetcher" class="container">
        <input type="text" ng-model="movieFetcher.movieId"></input>
        <button ng-click="movieFetcher.sendId(movieFetcher.movieId)">Fetch Details</button>
    </div>
</body>

My Angular Controller看起来像这样:

angular.module('testApp', []).controller('testController',['$http',function($http){
this.movieId = 197;
this.sendId = function(id){
    $http.post('/test',id).success(function(response){
     // does something on response
    });
}; }]);

我的节点服务器如下:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.text());
app.listen(8080);


app.post('/test', function(req, res) {
 var i = req.body;
 var url = 'http://www.imdb.com/title/tt' + i + '/';
 // i shows as undefined
 console.log("i is",i,"url is",url);
 res.send(url);
});

3 个答案:

答案 0 :(得分:0)

$http.post默认情况下发送的内容类型为application/json,因为您使用的是text/plain,您需要明确发送内容类型text/plain

$http({
  method: 'POST',
  url: '/test',
  headers: {
    'Content-Type': 'text/plain'
  },
  data: id
})
  

$http Docs设置HTTP标头

     

$ http服务会自动为所有请求添加某些HTTP标头。可以通过访问$ httpProvider.defaults.headers配置对象来完全配置这些​​默认值,该配置对象当前包含此默认配置:

     
      
  • $httpProvider.defaults.headers.common (headers that are common for all requests): Accept: application/json, text/plain, * / *

  •   
  • $httpProvider.defaults.headers.post: (header defaults for POST requests) Content-Type: application/json

  •   
  • $httpProvider.defaults.headers.put (header defaults for PUT requests) Content-Type: application/json

  •   

答案 1 :(得分:0)

将您的server.js更新为

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + '/public'));

而不是

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.text());

然后你应该没事。

答案 2 :(得分:0)

将传入的JSON转换为字符串,         var body =&#39;&#39 ;;         req.on(&#39; data&#39;,function(data){             body + = data;         });         req.on(&#39; end&#39;,function(){             var params = JSON.parse(body);             //回调函数             打回来;         });

然后读取你的数据,如body.id