我正在使用 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 HeadersThe $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/