Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

102
Views
Axios Post Body Empty with Express

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

you need to have a res.send() somewhere within this block

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)
    // });
});
about 4 years ago · Juan Pablo Isaza Report

0

Firstly to get a response from your backend, you need to specify what to receive by yourself, you can send the response as json by doing: res.json("..."). You should change the ... to any response you want to get back. And if you want to get your data back, you can put it there. You can also do res.send("...") to send a message after the request was completed

Secondly, you need to let your backend accept json data by adding this after the app variable. app.use(express.json());

Lastly, I would encourage you to you async function to make your code looks cleaner. You can change your post request code to something like this and let me know if it works.

app.post("/api/insert", async (req, res) => {
  try {
    const { cocktailName, cocktailMain } = req.body;
    const sqlInsert = await "INSERT INTO cocktail_recipes (cocktailName, cocktailMain) VALUES (?,?)";
  } catch (e) {
    console.log(e.message);
  }
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!