Post an object with fetch using react js and express API server Post an object with fetch using react js and express API server express express

Post an object with fetch using react js and express API server


body must be stringified + don't forget the content-type

 fetch('/todo/meterla',{    method: 'POST',    body: JSON.stringify({      task: self.refs.task.value    }),    headers: {"Content-Type": "application/json"}  })  .then(function(response){    return response.json()  }).then(function(body){    console.log(body);    alert(self.refs.task.value)  });


try using axios instead of fetch I rewrote ur code like this and it works perfectly

server

const express     = require('express');const { Client }  = require('pg');const bodyParser  = require('body-parser');const app         = express();const cors = require("cors");app.use(cors());app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true }));app.post('/api/insertUsers', function(req, res) {// console.log(req);console.log(req.body);res.send(req.body);}); app.listen(3001, () => { console.log('listening on port 3001');});

react (ensure you have axios installed)

handleSubmit(e){
e.preventDefault(); var data = { name: "zadiki", contact: "0705578809", email: "zadiki", message: "test", } console.log("wow"); var url = ' http://localhost:3001/api/insertUsers'; axios.post(url,data) .then(response=>console.log(response)) .catch(e=>console.log(e)) }


Looks like this is where the issue is.

constructor(props) {super(props);this.state = {data: ""};this.state_2 = {message: []};this.onSubmit = this.handleSubmit.bind(this);}componentDidMount() { fetch('/todo/1').then((response) => response.json()).then((responseJson) =>{  this.setState({    message: responseJson.data  });})}

In componentDidMount() you are setting the state for 'message'. But that is in this.state_2.

I would recommend not having this.state_2 and instead constructing your state like this:

this.state = {  data: '',  message: []}