【问题标题】:How to send data from React front-end to Nodejs Express back-end on button click如何在按钮单击时将数据从 React 前端发送到 Nodejs Express 后端
【发布时间】:2018-04-12 17:02:37
【问题描述】:

免责声明:我是 React 和 Nodejs 的新手,当然看过所有当前类似的帖子,但没有一个能够完全帮助我,所以请不要标记为重复。

在我的 Nodejs index.js 我有:

app.get('/list-certs', function (req, res) {
   fs.readFile("certs.json", 'utf8', function (err, data) {
       console.log( data );
       res.send( data );
   });
})

app.post('/list-certs', function (req, res) {
    res.send('POST request: ' + req.body.domain-input);
    console.log('post is working!')
});

在我的 React App.js 我有:

componentDidMount() {
  this.callApi()
    .then(res => {
      this.setState({
        json: res.map(x => x),
      })
    })
    .catch(err => console.log(err));
}


callApi = async () => {
  const response = await fetch('/list-certs');
  const body = await response.json();

  if (response.status !== 200) throw Error(body.message);
  return body;
};


handleChange(event) {
  this.setState({domainInputValue: event.target.value});
}


click() {
}


render() {
  return (
    <div className="App">

      <form action="http://127.0.0.1:8000/list-certs" className="add-cert-form" method="post">
        <h1>Add new domain</h1>
        <h5 className="domain-label">Name:</h5>
        <Input className="domain-input" value={this.state.domainInputValue} onChange={(e) => {this.handleChange(e)}}></Input>
        <Button onClick={this.click} className="domain-button" type='primary'>Add</Button>
      </form>
      .
      .
      .
}

当单击按钮domain-button 时,如何将输入字段domain-input 中的数据发送到我的后端?我知道click() 需要输入一些内容,但我不确定是什么。
任何帮助表示赞赏!

【问题讨论】:

    标签: node.js reactjs rest express post


    【解决方案1】:

    您的点击函数将如下所示:

    async click() {
        const { domainInputValue } = this.state;
        const request = await fetch('/echo/json', {
            headers: {
                'Content-type': 'application/json'
            },
            method: 'POST',
            body: { domainInputValue }
        });
    
    }
    

    【讨论】:

    • 好答案,只是为了避免混淆,您的request var 实际上是请求response 值;
    • 感谢您的帮助,但当我单击按钮时,我收到“无法发布 /list-certs”。我还缺少其他东西吗?我的 GET 和 POST 调用是否需要不同的路径?
    • @tnoel999888:我认为您需要使用 JSON.stringify({domainInputValue}) 对数据进行字符串化
    • @UmairAhmed 这是否在 click() 方法的“body:”声明中?
    • @Dyo 所以我应该把它改成const response而不是const request吗?
    猜你喜欢
    • 2022-01-28
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 2021-10-07
    • 1970-01-01
    相关资源
    最近更新 更多