首页 > 解决方案 > 调用按钮时,如何将反应 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 来执行此操作,并且没有遇到这些问题。任何帮助、方法、建议都非常受欢迎:)

请原谅我的无知,我只是来学习的。

标签: javascriptnode.jsreactjssails.jsaxios

解决方案


好的,所以我要做的第一件事是使用 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;            
        }

推荐阅读