sinafarheidar12
sinafarheidar12

Reputation: 115

Using express post with react

I'm trying to get familiar with using react and express in a todo app. I have created a post that I want to console.log an input that the user inputs. It runs fine but after i input some values and submit I get 'undefined' logged in the console.

export default function App() {

    const [todo, setTodo] = useState('');

    const classes = useStyles();

    const postData = () => {
      axios
      .post('/api/create', todo)
      .then((response) => console.log(response))
      .catch(err => {
        console.error(err);
      });
    }

  
    return (
      <Container maxWidth="sm">
      <Card className={classes.root} variant="outlined">
        <CardContent>
          <Typography variant="h5" component="h2">
            To Do List!
          </Typography>
          <Typography className={classes.pos} color="textSecondary">
            Keep track of everything you have to do
          </Typography>
        </CardContent>
        <CardActions>
          <form >
          <TextField name='item' id="standard-basic" label="Standard" onChange={e => setTodo(e.target.value)}/>
          <Button size="small" onClick={postData} >Submit</Button>
          </form>
        </CardActions>
      </Card>
      </Container>
    );
  }

Here is my post

const express = require('express');

const app = express();

app.use(express.urlencoded({extended: false}))
app.use(express.static('dist'));


app.post('/api/create', (req, res) => {
    console.log(req.body.item)
    res.send(req.body.item)
})

app.listen(process.env.PORT || 8080, () => console.log(`Listening on port ${process.env.PORT || 8080}!`));

Upvotes: 0

Views: 26

Answers (1)

Kvlknctk
Kvlknctk

Reputation: 670

If I understand your question correctly, you are looking for a value named item in the body. but you don't send this with react.

const postData = () => {
      axios
      .post('/api/create', {item : todo})
      .then(res => res.data)
      .then(result => console.log(result))
      .catch(err => {
        console.error(err);
      });
    }

Upvotes: 1

Related Questions