Molehole
Molehole

Reputation: 65

Localhost refuses connection from Javascript

I am making a single web app that takes information from MYSQL database and displays it on screen using AngularJS and NodeJS. I have set up a node.js server that gives out JSON file from a database. It works fine if I connect to it like this: 192.168.1.57:8888 which is my home server ip or remote connecting my server and using localhost:8888. Doing this downloads the JSON file on my computer.

However. If I'm using javascript to get JSON file from the server it gives me this error:

GET http://localhost:8888/ net::ERR_CONNECTION_REFUSED

I have tried connecting to the server with both AngularJS and JQuery and they both give the same error. I've also tried 127.0.0.1 and that doesn't work either. What can I do to fix it or can I do this with a better alternative way?

This is the server code in node.js

var http = require("http");
mysql = require("mysql");

var connection = mysql.createConnection({
user: "test",
password: "test",
database: "test"

});


http.createServer(function (request, response) { 

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

    connection.query('SELECT * FROM feedback;', function (error, rows, fields) { 
        response.writeHead(200, { 
            'Content-Type': 'x-application/json' 
        }); 

        response.end(JSON.stringify(rows)); 
    }); 
}); 


}).listen(8888);

this is the client side in angularJS:

(function(){
var app = angular.module('question', [ ]);

app.controller("ServerController", [ '$http', function($http){
    $http.get("http://localhost:8888").success(function(data,status,headers,config){
        console.log("success");
    }).error(function(data,status,headers,config){
        console.log("error");
    });

} ]);
}
)();

Upvotes: 2

Views: 3187

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075219

Taking a guess at it, you're running into the Same Origin Policy, which requires that the page making the ajax request be in the same origin as the resource it's requesting (or that the server serving the resource supports CORS and allows the page's origin).

Two different ways this might be hitting you (I can't tell which, the question doesn't give enough information):

  • If the browser code is running in a page loaded from the file system, not via HTTP, then it's a cross-origin request because the protocols don't match (file: vs. http:).

  • If the page has not been loaded from localhost:8888, but instead from some other port on localhost, then the origins don't match because the port numbers are different.

Upvotes: 1

Related Questions