Home > Blockchain >  How to send Json data to an API in React
How to send Json data to an API in React

Time:07-21

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

});

CodePudding user response:

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

CodePudding user response:

i think you can try this way

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