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???