javascriptnode.jsexpresspostaxios

how can i receive the body of an axios post request with express nodejs?


my browser side js code:

import axios from 'axios';

var testObject = {
   field : 'this is a test field'
}

axios.post('/create', testObject)
.then((res) => {
   console.log(res);
});

my nodejs code:

const express = require('express');
const path = require('path');

const app = express();

//middlewares
app.use(express.urlencoded({extended: false}));
app.use(express.static(path.resolve(__dirname, '../dist')));

app.post('/create', (req, res) => {
  console.log(req.body);
  res.send('this is the server response');
});

const port = 3000;
app.listen(port, () => {
  console.log('server listening on port ' + port);
});

my node js output:

server listening on port 3000
{}

my browser console output:

{data: "this is the server response", status: 200, statusText: "OK", headers: {…}, config: 
{…}, …}

please look that I'm alredy using a parser body middleware, the request is working fine but for some reason the server cant get the request body.


Solution

  • You have to use app.use(express.json())

    // parse application/json
    server.use(express.json());
    
    app.post('/create', (req, res) => {
      console.log(req.body);
      res.send('this is the server response');
    });
    

    You also have to update your ajax request with following:

    contentType: "application/json",
    data: JSON.stringify(hellodata),