本地主机拒绝来自 Javascript 的连接

Localhost refuses connection from Javascript

我正在制作一个网络应用程序,它从 MYSQL 数据库获取信息并使用 AngularJS 和 NodeJS 将其显示在屏幕上。我已经设置了一个 node.js 服务器,它从数据库中发出 JSON 文件。如果我像这样连接到它,它工作正常:192.168.1.57:8888 这是我的家庭服务器 ip 或远程连接我的服务器并使用 localhost:8888。这样做会在我的计算机上下载 JSON 文件。

不过。如果我使用 javascript 从服务器获取 JSON 文件,它会给我这个错误:

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

我尝试使用 AngularJS 和 JQuery 连接到服务器,但它们都给出相同的错误。我也试过 127.0.0.1 也没有用。我可以做些什么来修复它,或者我可以用更好的替代方法来解决这个问题?

这是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);

这是 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");
    });

} ]);
}
)();

猜测一下,您 运行 进入 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 并允许页面的来源)。

这可能会以两种不同的方式打击您(我不知道是哪一种,问题没有提供足够的信息):

  • 如果 浏览器代码 运行 在从文件系统加载的页面中,而不是通过 HTTP,那么它是一个跨源请求因为协议不匹配(file: vs. http:)。

  • 如果页面不是从 localhost:8888 加载的,而是从 localhost 上的某个其他端口加载的,则来源不匹配,因为端口号不同.