javascript - 如何从 Nodejs 中的 post 请求中获取正文?

标签 javascript angularjs node.js post express

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

我的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>

我的 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
    });
}; }]);

我的 Node 服务器看起来像:

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);
});

最佳答案

$http.post 默认情况下发送 application/json 的 Content-Type,因为您使用的是 text/plain,因此需要显式发送 text/plain 的 Content-Type。

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

From $http Docs Setting HTTP Headers

The $http service will automatically add certain HTTP headers to all requests. These defaults can be fully configured by accessing the $httpProvider.defaults.headers configuration object, which currently contains this default configuration:

  • $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

关于javascript - 如何从 Nodejs 中的 post 请求中获取正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35853231/

相关文章:

javascript - 在 HTML 中使用计时器平滑滚动

javascript - 为什么我得到 'Unexpected use of ' 位置'no-restricted-globals'?

AngularJS:如何测试将焦点放在元素上的指令?

angularjs - 使用自动 ng-bind 创建 ASP MVC 自定义 View

node.js - 如何在没有使用 socketio-jwt 进行身份验证的情况下发出和接收

javascript - 通过jquery解析google搜索

javascript - 通过 Ajax 请求时完成 OpenIDConnect 身份验证

javascript - Angular 复选框问题

oracle - 使用 node-oracle 将硬编码字符串减半

node.js - Node.js 的版本控制工具