Getting Bad Request 400 when getting json from URL in node.js
I keep getting a Bad Request error from the URL I'm calling in my node.js server file. any ideas?
I've tried external working URLS too, so it's not a localhost issue.
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(){});
});
Try adding slash '/
' character in the path field of your http.get
options object:
...
http.get({ host: 'localhost', port: 8888, path: '/json.php' }, function(response) {
...
Also you are missing res.end();
in your http server:
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);
...
精彩评论