I'm trying to submit post data from React Js to Express but there is no data been passed to body.
App.js from React
function submitForm(){
axios({
url: 'http://localhost:9000/api/submit-student',
method: 'POST',
body: {name: 'John Doe'}
})
.then(() => {
console.log('Data has been saved.')
})
.catch(() => {
console.log('Internal server error')
})
}
api.js
const express = require("express");
const router = express.Router();
router.post("/submit-student", function (req, res) {
res.send(req.body)
console.log(res)
});
module.exports = router;
I have set a testing data inside the body which will be passed to api.js that read the port 9000. The submission is fine. The only issue is that, the req.body is returning an empty json array {}. It read Data has been saved. message but the console.log(res) showing empty array at the body section.
there is no error appeared when submission. I even tried postman and it can retrieve the post data.
EDIT
I have bodyParser included in my server.js file.
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
app.use(cors())
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
const port = process.env.PORT || 9000;
const routes = require("./routes/api");
mongoose.connect("mongodb-url-here", {
useNewUrlParser: true
})
mongoose.connection.on('connected', ()=>{
console.log('Mongoose is connected!');
})
app.use('/api', routes);
app.listen(port, () => console.log(`Server up and running on port ${port} !`));
