【问题标题】:How do I pass a react DOM state's information to backend(NodeJS) when a button is invoked?调用按钮时,如何将反应 DOM 状态的信息传递给后端(NodeJS)?
【发布时间】:2018-06-24 18:09:47
【问题描述】:

我在前端使用他的逻辑,但实际上在后端接收数据时遇到了一些麻烦。我正在使用 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 执行此操作,但没有遇到这些问题。 任何帮助、方法、建议都非常受欢迎:)

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

【问题讨论】:

  • 当请求被触发时,您从服务器得到什么响应?尝试像这样传递标头,标头:{ 'content-type': 'application/json' },
  • 点击提交时出现什么错误?控制台中的任何错误?页面是否被重定向到错误的位置?

标签: javascript node.js reactjs sails.js axios


【解决方案1】:

好的,所以我要做的第一件事是使用命令sails generate api data 生成一个新的RESTful API。在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;            
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    相关资源
    最近更新 更多