How to execute a function on the node server by using vanilla javascript

问题: Okay so basically I'm trying to create a typing game that uses a JSON file as the database. I'm using Nodejs to manipulate the use of a .json file with the fs module. What...

问题:

Okay so basically I'm trying to create a typing game that uses a JSON file as the database. I'm using Nodejs to manipulate the use of a .json file with the fs module. What I want to do is have a main.js which operates the website's appearance which will contain a table of high scores, and I also want a player.js which will run on the back-end which updates a JSON file containing each player's name and high score.

So I was experimenting with it. I learned the hard way that require() is a node function. I want main.js to call a function from player.js and send it parameters.

var playerArr = player.updatePlayers("Rain", 30);

I know this doesn't work but the updatePlayers() function written with node in player.js returns an array and I want to set it to playerArr within main.js.

require() comes up with an error in the browser because its not a part of vanilla Javascript and I know it has to be run on a node server.

Is there any way to do this? It's for a school project and I'd love to be able to implement Nodejs and JSON into it.


Okay so everything's working except one crucial thing... the array isn't being sent back to the browser. I decided to use routes from express:

app.get("/:name,:score", returnScoreboard);
function returnScoreboard(request, response){
    let data = request.params;
    playerArr = updatePlayers(data.name, data.score);
    response.send(playerArr);
}

Now in my main.js, this is my code:

var playerArr;

var updatePlayer = new XMLHttpRequest();
updatePlayer.onreadystatechange = () => {
    playerArr = this.responseText;
}

updatePlayer.open("GET", "/Moo,100", true);
updatePlayer.send();

console.log(playerArr);

And I can't seem to get a response from into the playerArr. The JSON file that I'm using is getting updated correctly with a new object every time ({"name":"Moo", "score":100}) but it's not being assigned to playerArr. Please help!


回答1:

I suggest you have a Node backend and use something like https://expressjs.com/. You can use it to set up some endpoint(s). These endpoints would be called upon by your frontend JS code using Fetch or something of the like, https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch.

  • 发表于 2019-03-19 06:27
  • 阅读 ( 202 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除