1

So I see questions where people are saying they can't insert things into their database. My problem is worse than that: when I try to insert things into my database, none of my client side JavaScript works! I know this because the canvas is set, within the first couple of lines of the main script, to fill the entire window, but when I tried to insert the score into my database the canvas showed up as the default size. When I commented out this code it suddenly worked again:

const check = await fetch('/api');
const checkData = await check.json();

  if (score > checkData.highscore){
    let highscore = score;
    const data = { highscore };
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    };
    const response = await fetch('/api', options);
    const json = await response.json();
    console.log(json);
}

I thought maybe it was because there was no high score in the database, so in the serverside index.js I did this:

let highscore = 0;
const data = { highscore };
const options = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
};
database.insert(data);

(Again, I commented it out, partially because I thought it was breaking the client.js and partially because I was done with it and don't want the high score to reset every time I restart the server but I didn't want to delete the code yet just in case) But even with that, it still didn't work, so I had to delete that first bit of code for my game to run at ALL. The entire thing is visible at https://repl.it/@RaphaelMorgan/RPhighscore if you think the error might be somewhere else, but I feel like it's probably in that first bit of code or maybe in the server side part of that, which is just:

app.get('/api',(request,response)=>{
  database.find({},(err,data)=>{
    if (err){
      console.log(err);
    }
    response.json(data);
  })
});

app.post('/api',(request,response)=>{
  const data = request.body;
  database.insert(data);
  console.log(database);
  response.json(data);
});

Does anyone know what's going on here???

Ashish Kamble
  • 2,555
  • 3
  • 21
  • 29
  • have you checked if database.insert isn't an async function, hence, needs callback? – Lhew Jul 22 '20 at 12:28
  • @Lhew what do you mean by that? I'm not too experienced with async functions, I only used it because I was taught to in a tutorial for saving to databases – Raphael Morgan Jul 22 '20 at 12:58
  • 1
    Remove the `await` from your code in _client.js_. I guess the reason is that you are forcing the program to wait for a asynchronous response, hence it gets stuck waiting forever. But no Node.JS expert here so what do I know... **Edit:** or this [await can only be used _inside_ async functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) – Fullslack Jul 22 '20 at 13:27

0 Answers0