1

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.

enter image description here

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} !`));
0

2 Answers 2

1

Change body option to data for axios. See docs about how to send a POST request.

api.js:

const express = require('express');
const router = express.Router();

router.post('/submit-student', function(req, res) {
  console.log(req.body);
  res.send(req.body);
});

module.exports = router;

server.js:

const express = require('express');
const cors = require('cors');
const api = require('./api');

const app = express();
const port = 9000;

app.use(cors());
app.use(express.json());
app.use('/api', api);

app.listen(port, () => console.log('server start'));

client-side:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  
</head>
<body>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
  axios({
    url: 'http://localhost:9000/api/submit-student',
    method: 'POST',
    data: { name: 'John Doe' }
  })
    .then(() => {
      console.log('Data has been saved.');
    })
    .catch(() => {
      console.log('Internal server error');
    });

  </script>
</body>
</html>

Server Logs:

server start
{ name: 'John Doe' }
Sign up to request clarification or add additional context in comments.

1 Comment

You are right! It's because of the body. I switched to data and it's working now. Thank you very much!
0

solution 1:

you need the middleware "body parser"

add this into your app.js or server.js file ( server side )

var bodyParser = require('body-parser')
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

Solution 2: ( react side )

function submitForm(){
    axios({
        url: 'http://localhost:9000/api/submit-student',
        method: 'POST',
        body: JSON.stringify({name: 'John Doe'}), // body must be raw ( as a plain string should do it )
        headers: { 'Content-Type': 'Application/json'} // need the type of the content that is being send
    })
    .then(() => {
        console.log('Data has been saved.')
    })
    .catch(() => {
        console.log('Internal server error')
    })
}

in axios the body that you send to the server should be raw and the call contain the header { 'Content-Type': 'Application/json'}

7 Comments

I have this parser in my server.js
try solution 2. i think it need a raw data into the body
Tried it and unfortunately, it's still the same :(
what is the response of the axios call? is it a 404? also console.log(req), should be before res.send(req.body)
It returned 200.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.