Home > Software engineering >  Axios Post Body Empty with Express
Axios Post Body Empty with Express

Time:08-03

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

CodePudding user response:

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)
    // });
});

CodePudding user response:

Change this line:

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

to 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.

CodePudding user response:

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);
  }
});
  • Related