[英]How to get body from a post request in Nodejs?
我正在使用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>
我的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);
});
默認情況下, $http.post
發送一個application/json
的Content-Type,因為您使用的是text/plain
,所以您需要顯式發送一個text/plain
的Content-Type。
$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
將您的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());
那你應該沒事的。
將傳入的JSON轉換為字符串,var body =''; req.on('data',function(data){body + = data;}); req.on('end',function(){var params = JSON.parse(body); //回調函數callback;});
然后讀取您的數據,例如body.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.