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;