前台用的是xhr向后台发请求,后台是nodejs接收前台数据,不懂为什么node接收的值总为空的{};
如果前台换成angularJS的$http来发请求,后台则可以成功接收数据
//HTML
<body ng-app="app" ng-controller="ctrl">
<input type="text" class="name">
<input type="button" value="submit" class="submit" ng-click="sendData()">
</body>
//XHR2
<script>
var btn = document.querySelector('.submit');
function sendText() {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/xhr', true);
xhr.withCredentials = true;
var name = document.querySelector('.name');
var data = {name: name.value};
xhr.onload= function(){
if(xhr.status == 200){
console.log(xhr.response);
}
};
xhr.onerror= function(){
console.log('error occur')
};
xhr.send(data);
}
btn.onclick = function() {
sendText();
}
</script>
//angular $http
<script>
angular.module('app',[])
.controller('ctrl', function($scope, $http){
var name = document.querySelector('.name');
$scope.sendData = function(){
$http({
method: 'POST',
url: '/xhr',
data: {name: name.value}
}).then(res=>{
console.log(res);
});
};
});
<script>
//app.js
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
app.listen(3000, function(err) {
if (err) console.log(err);
console.log('server running on port 3000');
});
app.use(express.static('js'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get('/xhr', function(req, res) {
res.sendFile(__dirname + '/xhr.html');
});
app.post('/xhr', function(req, res) {
console.log(req.body);//空的{}
res.end('hello');
});
XHR2 后台接收数据的截图
angularJS $http 后台接收数据的截图
我测试过了,是你发送的数据有问题,按你所写的,发送出去的内容是这样:
抓包结果:
并不是你期望的json字符串,如果你实在想用json,得把js对象转换为json字符串.
建议使用
name1=value1
格式, 不行的原因是你没有说明内容的类型,应该在open之后加上xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
就可以了.