Javascript 将mongoDB从本地移动到外部,现在应用程序显示错误连接

Javascript 将mongoDB从本地移动到外部,现在应用程序显示错误连接,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我最近有一个应用程序,我将MongoDB本地保存到我的PC上,它像做梦一样工作,我现在修改了这个程序,使DB可以从外部访问,但现在我有连接问题,请有人指出我哪里出了问题 在我的server.js文件中,我有以下内容: var uri = "mongodb+srv://kayleigh:notMyRealPassword@cluster0-ikkkw.mongodb.net/Hangman?retryWrites=true&w=majority"; Chrome控制台中的错误是:GETh

我最近有一个应用程序,我将MongoDB本地保存到我的PC上,它像做梦一样工作,我现在修改了这个程序,使DB可以从外部访问,但现在我有连接问题,请有人指出我哪里出了问题

在我的server.js文件中,我有以下内容:

var uri = "mongodb+srv://kayleigh:notMyRealPassword@cluster0-ikkkw.mongodb.net/Hangman?retryWrites=true&w=majority";
Chrome控制台中的错误是:
GEThttp://localhost:9000/random 网络::错误连接被拒绝

在名为script.js的文件中,我有一些GET请求,我认为这可能是问题的原因,我是否需要替换其中声明
的部分http://localhost:9000/getPlayers“
?”

// search database for the players name that's just been entered
$.get("http://localhost:9000/getPlayers", function(data) {
    console.log(JSON.stringify(data));

    var counter = 0;

    // loop through each player (value) within list of players (data)
    $.each(data, function(key, value){
        // if the name is equal to person name, increment counter.
        if (value.name == personName)
        {
            counter++;

            // updating player score into DB by 5 each win.
            let playerData = {"name": personName, "score": value.score + personScore};

            updatePlayerScore(playerData);
            $("#wonOrLost").text("Your score has been updated on the leadership board!");
            return false;
        }
    });

    if (counter == 0){
        // Not in database, so adding new player.
        let playerData = {"name": personName, "score": personScore};

        addPlayer(playerData);
        $("#wonOrLost").text("Your score has been added to the leadership board!");
    }
});
server.js文件还包含以下/random代码(从mongoDB获取一个随机单词):


因此,您当前遇到的连接错误与mongodb无关。您的server.js看起来是nodejs express服务器的一部分,该服务器将被调用。(您的express服务器正在承载此网页)

如果您已将mongo和express web服务器移动到新服务器,则需要使用新外部服务器的IP更改localhost,使其成为http://:9000/GetPlayer。(我假设您在代码的html页面中使用jquery调用它)

这里需要注意的其他事项还包括新的服务器防火墙(9000不是标准的web服务器端口),如果您在express server中设置绑定地址(app.listen(9000,'127.0.0.1'),则127.0.0.1将是绑定地址),然后也将其设置为服务器公共IP

app.get("/random", async function(request, response) {
    var randomWord = await random();
    response.send(randomWord.text);
});

// This function goes to my db and counts all of the words in there to randomly choose the ID 
// that's associated with a word. It will return the String.
async function random () {
    var words = await db.getWords();
    var count = words.length;
    var randomId = Math.floor(Math.random() * count);
    console.log(randomId);
    var randomWord = await db.getWordById(randomId);
    console.log(randomWord);
    return randomWord;
}