0

I'm trying to send data from React to Node. I know that I can do it through 'action' and 'method' in the form tags, but I'm trying to do it through fetch. In the Node post call, the console.log('POST received in Node') is coming back fine but the console.log(request.body) is giving me undefined. Why is this happening?

Node:

const express = require('express');
const application = express();

application.get('/', (request, response) => {
    response.send('Basic route');
});

application.post('/register', (request, response) => {
    console.log(request.body);
    console.log('POST received in Node');
});

application.listen(8080, () => {
    console.log('Connected on PORT 8080');
});

React:

import React, { useState } from 'react';

const Register = () => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');

    const readUsername = (e) => {
        setUsername(e.target.value);
    };

    const readPassword = (e) => {
        setPassword(e.target.value);
    };

    const postData = async () => {
        await fetch('/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                username,
                password,
            }),
        }).then(console.log('POST made from component'));
    };

    return (
        <>
            <h1>Register</h1>
            <input type="text" placeholder="username" onChange={readUsername} />
            <br/>
            <input type="password" placeholder="password" onChange={readPassword} />
            <br/>
            <button onClick={postData}>Send</button>
        </>
    );
};

export default Register;
5
  • In your post request, try: username: username and password: password. Not just username, password Commented Sep 21, 2021 at 0:46
  • @hisam I still get back undefined Commented Sep 21, 2021 at 0:47
  • 1
    You need some body-parsing middleware like application.use(express.json()) Commented Sep 21, 2021 at 1:04
  • @Phil That worked thank you very much. Feel free to put that in the answers if you want and I can mark it as correct, but don't worry about it if you don't feel like it for whatever reason. Commented Sep 21, 2021 at 1:09
  • @hisam nothing wrong with shorthand property names Commented Sep 21, 2021 at 1:10

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.