Having a tough time passing some data to express. I am trying to send some data I gather from a form. The form value is being updated correctly. But when I hit my end point I do not know how to log out what I am passing. Any pointers would be much appreciated.
Express:
app.post('/something-to-post', cors(corsOptionsDelegate), (req, res)=> {
//how do I log what I am passing from the form
console.log('full name:', req.data);
});
React
import React, {useState} from "react";
import axios from "axios";
const Form = () => {
const [fullName, setFullName] = useState('');
function handleInputChange(event) {
setFullName(event.target.value); // updates state properly
}
function post(event){
event.preventDefault();
console.log('full name:', fullName); // logs out correctly
axios.post('http://localhost:9000/something-to-post', {name: fullName})
.then(response => {
// todo
})
.catch(error => {
// todo
})
}
}
return (
<form onSubmit={post}>
<input type="text" value={fullName} onChange={handleInputChange}/>
<button type="submit">Submit</button>
</form>
)
};
export default Form;
You can do it like this code below:
FrontEnd:
import React, {useState} from "react";
import axios from "axios";
const Form = () => {
const [fullName, setFullName] = useState('');
function handleInputChange(event) {
setFullName(event.target.value); // updates state properly
}
function post(event){
event.preventDefault();
console.log('full name:', fullName); // logs out correctly
axios.post('http://localhost:9000/something-to-post', {name: fullName})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error.data)
})
}
return (
<form onSubmit={post}>
<input type="text" value={fullName} onChange={handleInputChange}/>
<button type="submit">Submit</button>
</form>
);
}
export default Form;
Backend:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.post('/something-to-post', (req, res) => {
console.log(req.body);
console.log(req.body.name);
const response = {
success: true,
code: 200,
message: 'Data from backend',
data: req.body
}
res.status(200).send(response);
})
app.listen(9000, () => {
console.log('Server is up');
})
I hope it can help you.
I needed to install and utilize npm i body-parser for req.body.name to work for me.
If you're using the latests version of express, then you should not to install body parser. You can use express. That code above it's an example that you've not needed to install body-parser.