是否有一种方法从js文件发送数据到express服务器而不使用表单?



我是新来的,如果我错过了一些最佳实践,我很抱歉。

我正在创建一个数独游戏,使用express, js, html和mongoDb.

现在我正在尝试创建一个统计系统。我想发送一个数据当你赢得数独,到快递服务器(server.js),并更新mongoDb。

我知道我可以用POST方法发送数据,但我只知道使用html表单,但在这种情况下,我想通过js函数发送它。

js文件: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()
}
}

我已经尝试使用export将函数发送到server.js,改变信息,但我不能,因为game.js链接到game.html由于某种原因,输出不起作用。

我也尝试使用ejs我渲染了ejsserver.js(表达),但我不能改变任何数据在ejs文件。

然后我试着研究其他方法来制作这个,但我没有找到任何东西

是否有办法发送数据到server.js通过这个函数?

这是一个向后端发送带有一些数据的post请求,然后从后端向前端发送响应数据的示例。

//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 = req.body
//should print test
console.log(body.myData)
//returning data back to frontend
return res.json({
status: 'success',
response: 'dataRecieved'
})
}

是的,你可以在你的函数中使用fetch API来发送POST请求到你的服务器。您需要以服务器期望的格式发送数据(例如JSON)

下面是一个使用fetch() 发送post请求的示例https://googlechrome.github.io/samples/fetch-api/fetch-post.html

有关fetch API的更多详细信息,请参见:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

或者这个线程:读取:POST JSON数据

最新更新