繁体   English   中英

如何将 Json 数据发送到 React 中的 API

[英]How to send Json data to an API in React

我的前端有以下内容:注意:我的 JSON 文件处于状态

    const postData = () => {
        console.log("This is our data", state);
        const url = "http://localhost:3000/postData";
        fetch(url, 
        {method: 'POST', // or 'PUT'
        headers: { 'Content-Type': 'application/json',},
        body: JSON.stringify(state),
    })
    .then(response => response.json())
    .then(data => {
  console.log('Success:', data);
})
.catch((error) => {
  console.error('Error:', error);
});

}

这个前端正在工作。 但是,我想将此数据发布到 API,以便当有人键入时:

本地主机:3000/postData

他们必须在前端获取处于我状态的 JSON 文件

这是我正在努力的后端代码:

app.post("/postData", (req, res) => {
    console.log(req.body);
    const result = req.body.state
    res.send(result);

});
body: JSON.stringify({
            state: state,
        })

我想你可以试试这种方式

this.apiService.post('URl', body).then((data) => {
            if (data) {
            }
        });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM