我正在使用快速Web框架并尝试从angularjs发出$ http请求。我将数据传递给客户端请求,但服务器没有收到请求,原因不明。请帮忙。
server.js
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io')(server);
var path = require('path');
var fs = require('fs');
app.use(express.static(path.join(__dirname, 'public')));
app.post('/readTfile',function (req,res) {
console.log('i received a request');
console.log(req.body);
});
server.listen(3000);
and angular html
<html>
<head>
<title>File tream 2</title>
<script type="text/javascript" src="javascripts/angular.js"></script>
</head>
<body>
<h2>File tream 2 AngularJS</h2>
<div ng-app = "mainApp">
<div id="readfile" ng-controller = "Ctrl1">
<div>{{myfiledata}}</div> </br></br>
</div>
</div>
</body>
<script>
var mainApp = angular.module("mainApp",[])
mainApp.controller('Ctrl1', function ($scope, $http) {
var filename = 'D:\\myapp\\public\\test.txt';
var obj = {"filename" : filename};
$scope.myfiledata = 'result';
$http({
url: '/readTfile',
method: "POST",
data: JSON.stringify(obj),
//timeout: canceller.promise,
headers: {'Content-Type': 'application/json','charset' : 'utf-8'}
}).success(function(result) {
console.log(result);
$scope.myfiledata = 'result';
}).error(function(data, status) {
console.log(data);
});
});
</script>
</html>
在控制台上我对req.body
未定义我收到了一个请求
未定义
请帮我解决这个问题。
答案 0 :(得分:8)
您需要使用中间件从传入流中读取POST请求的正文,并将其从JSON解析为Javascript对象。它不会自动地以req.body
结尾。简单JSON主体的通常中间件是使用body-parser middleware。
const bodyParser = require('body-parser');
// other stuff here
// read and parse application/json
app.use(bodyParser.json());
app.post('/readTfile',function (req,res) {
console.log('i received a request');
console.log(req.body);
});
并且,要使此中间件工作并自动识别您发送了JSON,您必须确保帖子设置了正确的内容类型。