Axios Post Body Empty with Express

Issue

I’m trying to send over two pieces of text data from my React frontend to an Express backend but whenever I do the post command with Axios the body appears as {} in the backend and I cannot use it. My code is listed below.

Client (App.js):

import { useState, useEffect } from 'react';
import React from 'react'
import './App.css';
import Axios from 'axios'

function App() {

  const [cocktailName, setCocktailName] = useState("");
  const [cocktailMain, setCocktailMain] = useState("");

  const submitRecipe = () => {
    const recipeData = {"cocktailName": cocktailName, "cocktailMain": cocktailMain};
    Axios.post('http://localhost:3001/api/insert', recipeData).then(() => {alert('successful insert');});
  }

  return (
    <div className="App">
      <h1>CRUD Application Test</h1>
      <div className='InputForm'>
      <label> Cocktail Name: </label>
      <input type="text" name="Cocktail Name" onChange={(e)=> 
      {setCocktailName(e.target.value);}}/>
      <br></br>
      <label> Cocktail Main Ingredient: </label>
      <input type="text" name="Cocktail Main Ingredient" onChange={(e)=> {
      setCocktailMain(e.target.value)}}/>
      <br></br>
      <button onClick={submitRecipe}>Submit</button>
      </div>

    </div>
  );
}

export default App;

Server (App.js):

const app = express()
const mysql = require('mysql')
const bodyParser = require('body-parser')
const cors = require('cors')

const db = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'cruddatabase'
});

app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));

app.post('/api/insert', (req, res)=> {
    console.log(req.body)
    const cocktailName = req.body.cocktailName;
    const cocktailMain = req.body.cocktailMain;
    console.log(cocktailName)
    console.log(cocktailMain)
    //This is where i'll eventually insert it into a database
    const sqlInsert = "INSERT INTO cocktail_recipes (cocktailName, cocktailMain) VALUES (?,?)"
    // db.query(sqlInsert, [cocktailName, cocktailMain], (err, result) => {
    //     console.log(err)
    // });
});

app.listen(3001, () => {
    console.log("running on port 3001")
});

Any help at all is greatly appreciated.

Solution

Change this line:

app.use(bodyParser.urlencoded({extended: true}));

With this one:

app.use(express.json());

Axios send a JSON when you give an object as data without specifying the Content-Type like you did. So urlencoded is not the right set here.

Answered By – yousoumar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published