Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

101
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda