【发布时间】:2018-01-30 22:52:39
【问题描述】:
我正在使用 ajax 在前端运行脚本(通过在“/get?time=”中使用路由的“get”方法)试图从 nodejs 代码中的后端获取数据。但是程序在“res.send()”处停止。然后前面没有任何反应。任何人都可以提供任何想法来解决它吗?提前致谢。
前端
var config = {
apiKey: "AIzaSyAUUcpvcottIkYXfpwAZfT4axxxxxxxxxx",
authDomain: "test-9caab.firebaseapp.com",
databaseURL: "https://test-9xxxx.firebaseio.com",
projectId: "test-9xxxx",
storageBucket: "test-9xxxxappspot.com",
messagingSenderId: "1280039xxxxxx"
};
firebase.initializeApp(config);
function get(){
var req = new XMLHttpRequest();
req.open("get","/get?time="+time);
req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
req.onload = function(){
var data = JSON.parse(req.responseText);
show(data);
};
req.send();
}
function show(data){
var list = document.getElementById("list");
list.innerHTML="";
for(var i=0; i<data.length; i++){
list.innerHTML=data[i].time.bold()+"<br/>"+data[i].temp+"<br/>"+data[i].humid+""+"<hr/>"+list.innerHTML;
time =data[i].time+1;
}
}
var time=0;
window.onload = function(){
get();
window.setInterval(get, 10000);
}
后端
app.use(express.static("public"));
app.get("/get", function (req, res) {
var time = req.query.time;
info.orderByChild("time").startAt(time).once("value",function(snapshot){
var total = snapshot.numChildren();
var messages =[];
snapshot.forEach(function(itemSnapshot){
messages.push(itemSnapshot.val());
if(messages.length >=total){
res.json(messages);
}
})
});
});
并在服务器启动并运行时使用 localhost:5438/N01_index.html 在 Chrome 上运行。
然后我在控制台上收到错误消息
N01_index.html:45 GET http://localhost:5438/get?time=0 net::ERR_CONNECTION_REFUSED
Failed to load resource: net::ERR_EMPTY_RESPONSE get?time=0
【问题讨论】:
-
你确定你的代码执行了
res.json,这个错误意味着你的服务器没有响应任何东西,不仅body还有status。
标签: javascript node.js ajax