简体   繁体   中英

How to send Json data to an API in React

I have the following on my frontend: Note: My JSON file in a state

    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);
});

}

This front end is working. However, I want to post this data to an API such that when someone types:

localhost:3000/postData

They must get my JSON file that was in my state on the front end

Here is the backend code that I'm struggling with:

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

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

I think you can try this way

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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