我是Node.js
和JavaScript
的新手,我希望在搜索并找不到解决方案后能得到一些帮助。
我正在尝试使用XMLHttpRequest方法将JSON对象发送到Node.js服务器,该服务器包含2个元素(经度和纬度)的数组。这是客户端JavaScript代码:
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var location = [position.coords.latitude, position.coords.longitude];
console.log(location);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/locationdata', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function () {
console.log(this.responseText);
};
xhr.send(location);
});
} else {
console.log('Geolocation is not supported by this browser.');
}
}
服务器接收对象没有任何问题。但是,当我尝试将对象发送回客户端时,我得到一个未定义的值作为响应。这是Node.js脚本:
var html =
fs.readFile(__dirname + '\\public\\index.html', function(err, data) {
if (err){
throw err;
}
htmlFile = data;
});
var server = http.createServer(function (request, response) {
if (request.url == "/") {
response.writeHead(200, {"Content-Type": "text/html"});
response.write(htmlFile);
break;
};
if (request.method == 'POST' && request.url == "/locationdata") {
var postdata = '';
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function() {
var postdata = body;
console.log(postdata);
});
response.writeHead(200, {"Content-Type": "application/json"});
response.write(JSON.stringify(postdata));
}
response.end();
});
server.listen(3000);
可能是我在实际请求结束之前发送了响应,但我不确定。有任何想法吗?
答案 0 :(得分:2)
您没有在响应之前等待请求数据,这会导致您没有任何回应。这样做:
if (request.method == 'POST' && request.url == "/locationdata") {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function() {
response.writeHead(200, {"Content-Type": "application/json"});
response.end(body);
});
return;
}