2011-05-14 137 views
0

我一直收到來自我在我的node.js服務器文件中調用的URL的錯誤請求錯誤。有任何想法嗎?在node.js中從URL獲取json時出現錯誤請求400

我試過外部工作URLs,所以它不是本地主機問題。

var http = require('http'), 
io = require('socket.io'); 

server = http.createServer(function(req, res){ 
res.writeHead(200, {'Content-Type': 'text/html'}); 
}); 
server.listen(8181); 

// socket.io 
var socket = io.listen(server); 

socket.on('connection', function(client){ 

function getMessages() { 

    http.get({ host: 'localhost', port: 8888, path: 'json.php' }, function(response) { 

     var data = ""; 
     response.on('data', function(chunk) { 
      data += chunk; 
     }); 

     response.on('end', function() { 

      socket.broadcast(JSON.parse(data)); 
      //console.log(data); 
      //socket.broadcast('{ "alrt": "YES", "message": "Something is wrong!" }'); 
      //socket.broadcast('hi'); 
     }); 

    }); 

} 

setInterval(getMessages, 1000); 

client.on('message', function(){}) 
client.on('disconnect', function(){}); 

}); 

回答

2

嘗試增加斜槓 '/' 字在你的http.get的路徑選擇Field對象:

... 
http.get({ host: 'localhost', port: 8888, path: '/json.php' }, function(response) { 
... 

而且你缺少你的HTTP服務器res.end();

var http = require('http'), 
    io = require('socket.io'); 

server = http.createServer(function(req, res){ 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.end(); 
}); 
server.listen(8181); 
...