伙计们,我是node / express的新手,我正在使用express构建应用程序,有一个按钮我想单击以将我的数据保存到数据库(MongoDB)中。.但是我不想收到此请求特定端点..我的意思是我想将数据发送到MongoDB而不刷新或重定向页面..以及在将数据存储在MongoDB中之后,我想服务器在同一页面中通知我它成功完成了..我可以用来做什么那..我希望你明白我的意思和感谢。
答案 0 :(得分:0)
您可以发送XMLHttpRequests或在前端使用fetch API。
或者您可以选择加入外部库,例如Axios或jQuery's ajax
答案 1 :(得分:0)
按钮中有一个名为onClick的事件,该事件将在用户单击时触发,在该事件上,您将发送HTTP请求(发送请求的方式很多,但我建议您使用Axios)
const axios = require('axios');
const sendData = (userFirstName,userLastName)=>{
axios.post('/operation', {
firstName: userFirstName, // pass your data as object
lastName: userLastName
})
.then(function (response) {
// here will be the call back when request sent with success
// so you can do your stuff
console.log(response);
})
.catch(function (error) {
// if the request failed for some reason , you can show something to user
console.log(error);
});
}
<button onClick={()=>{sendData('John','Doe')}}> send data to express route </button>
在您的快速后端应用程序中,在我们的示例中,您应该有一个名称为operation
的终结点(API),它将接收您的Axios数据并使用数据库进行所需的工作