javascript - 调用按钮时,如何将反应 DOM 状态的信息传递给后端(NodeJS)?
问题描述
我在前端使用他的逻辑,但实际上在后端接收数据时遇到了一些麻烦。我正在使用 Sails.js 框架。有什么建议么?
handleSubmit = () => {
// Gathering together the data you want to send to API
const payload = {
subject: this.state.subject,
message: this.state.message,
};
this.handleAjaxRequest(payload);
};
// 向后端发送数据的方法 // 制作req - 我这里用的是Axios。
handleAjaxRequest = (payload) => {
let request = axios({
method: 'post',
url: '/api/',
data: payload,
headers: 'Content-Type: application/json'
});
// 处理来自后端的响应。
request.then(response => {
console.debug(response.data);
})
.catch(error => {
console.error(error);
})
};
我曾经使用 Express 来执行此操作,并且没有遇到这些问题。任何帮助、方法、建议都非常受欢迎:)
请原谅我的无知,我只是来学习的。
解决方案
好的,所以我要做的第一件事是使用 command 生成一个新的 restful API sails generate api data
。在package.json
文件中,我设置了一个包含后端端点的代理,就像这样"proxy": "http://localhost:1337"
- 我的意思是,你不需要这样做,但如果你不这样做,那么你必须在每个请求中包含这个 URL 部分。因为它不会改变,所以这样做非常方便。
在前端,我创建了一个函数sendData()
,它从我以前的组件中获取必要的数据(取决于用户选择的内容)并将该数据发送axios
到后端-->
sendData = () => {
const { relYear } = this.props.history.location.state.dev;
const { relMonth } = this.props.history.location.state.dev;
const selectedMonth = moment().month(relMonth).format("MM");
const finalSelect = parseInt(relYear + selectedMonth, 10);
axios.post('/data', { 'selectedDate' : finalSelect })
.then(res => console.log('Data send'))
.catch(err => console.error(err));
}
在后端,我获取数据,进行计算并将结果发送回我的应用程序的前端。-->
getApiData = () => {
let apiData = [];
axios.get('/data')
.then(res => {
let first = Object.values(res.data.pop()).shift(); // Getting the relevant 'selectedDate'
apiData.push(first);
}).catch(err => console.error(err));
return apiData;
}
推荐阅读
- java - 数据插入外部 sqlite 数据库但未保存在 android studio
- php - 重定向到有效的子域
- javascript - 在我调整浏览器窗口大小之前,Swiper 无法正常工作
- spring-boot - 春天云:RestTemplate postForObject 无法发送请求正文
- php - 如何在 Laravel 中为请求发送多个响应?
- model-view-controller - 控制器方法不存在。但实际上是存在的。不通过请求传递值
- coq - 在 Coq 中如何划分两个 Nat?
- c++ - is there any way to partial instance a c++ template
- php - 将行移动到另一个表并插入其他值
- c# - 带任务的异步/等待,重构方法