I am new here, Sorry if I miss something from the best practices.
I'm creating a sudoku game, using express, js, html and mongoDb.
Now I'm trying to create a statistics system. I would like to send a data when you wins the sudoku, to the express server (server.js) and after update the mongoDb.
I know I can send a data with the POST method, but I only know using the form html, but in this case I want to send it by the function js.
The js file: game.js
let cells = document.querySelectorAll('.div-cell'); // get the cells of the sudoku board
function checkWin() {
const db = getDb() // get the localStorage db (there is sudoku informationo, like the solution)
curentBoard = ''
for (let i = 0; i < 81; i ) {
if (cells[i].textContent === '') { // check if the cell is blank
curentBoard = '-'
} else {
curentBoard = cells[i].textContent
}
}
if (curentBoard === db.solution) { //check if the board is equal the solution
// Here would be the code to send the data to the server
alert('You won!')
newGame()
}
}
I've tried to use export to send the function to the server.js, to change the information, but I can't because the game.js is linked to the game.html, and for some reason the export doesn't work. Also for import.
I also tried to use ejs files, I rendered the ejs file sending the data statistics, by the server.js (express) but I couldn't change any data in the ejs file.
Then I tried to research other methods to make this, but I didn't find anything
Is there a way to send a data to the server.js by that function?
CodePudding user response:
Here is an example of sending a post request with some data to the backend then sending back a response data from backend to frontend.
//front end
fetch('api/server', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
myData: "test"
})
})
.then((res) => res.json())
.then(data => {
if (data.status == 'success') {
//when data is returned from backend
const response = data.response
console.log(response) //should print dataReceived
}
})
//backend
const handler = async(req, res) => {
//accessing data sent from front end
const body = JSON.parse(req.body)
//should print test
console.log(body.myData)
//returning data back to frontend
return res.json({
status: 'success',
response: 'dataRecieved'
})
}
CodePudding user response:
Yes, you can use fetch API inside your function to send POST request to your server. You need to send the data in the format that server expects (e.g. JSON)
here is an example of sending post request using fetch()
https://googlechrome.github.io/samples/fetch-api/fetch-post.html
for more details about fetch API see : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
or this thread : Fetch: POST JSON data