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;
phershbe
  • 169
  • 4
  • 12
  • In your post request, try: `username: username` and `password: password`. Not just `username, password` – hisam Sep 21 '21 at 00:46
  • @hisam I still get back undefined – phershbe Sep 21 '21 at 00:47
  • 1
    You need some body-parsing middleware like `application.use(express.json())` – Phil Sep 21 '21 at 01: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. – phershbe Sep 21 '21 at 01:09
  • @hisam nothing wrong with [shorthand property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#new_notations_in_ecmascript_2015) – Phil Sep 21 '21 at 01:10

0 Answers0