[Fixed] I should get body from post request with req.body.item?

Issue

I learned how to get body data from post request when using express. Most example codes represented that req.body.item should be able to get the value I want to use, for example, to insert value into a table.

But I couldn’t get the value with req.body.item but could finally get it with req.body.body.value. Am I not getting the post body value in the correct way, or this is just not a problem?

Node.js
  v14.15.4
Nuxt.js
  @ v2.15.4
Vue.js
  [email protected]
Express
  ^4.17.1

(expense.vue), Updated with correct code
post form data to "books/books/add"

<template>
  <div>
    <div class="main">
      <h3>please type expense name and amount</h3>
      <form @submit.prevent="addToBookDB">
        <label for="name_expense">expense name: </label>
        <input v-model.trim="expenseTitle" />
        <label for="price_expense">expense amount: </label>
        <input v-model="expenseSummary" />
        <input type="submit" value="Submit" />
      </form>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import axios from 'axios'

Vue.config.productionTip = false

export default {
  data () {
    return {
      expenseTitle: 'Title',
      expenseSummary: 'Summary',
    }
  },
  methods: {
    addToBookDB (event) {
      console.log(event)
      const formData = {
        expenseTitle: this.expenseTitle,
        expenseSummary: this.expenseSummary
      }
      console.log(JSON.stringify(formData))
      //<<wrong code↓>>
      //axios.post('books/books/add', {
      //  headers: {
      //    'Content-Type': 'application/json'
      //  },
      //  body: formData
      //<<correct code↓>>
      axios.post('books/books/add', formData
      ).then((response) => {
        console.log(response)
        return response
      }).catch((response) => {
        console.log(response)
        return response
      })
    }
  }
}
</script>

(books.js), Updated with correct code
insert received post data into table

const express = require('express')
const app = express()

app.use(express.json())
app.use(express.urlencoded({
  extended: true
}))

app.get('/books', (req, res) => {
  // (omitted)
})

app.post('/books/add', (req, res, next) => {
  const mysql = require('mysql')
  const connection = mysql.createConnection({
    host: '***.*.*.*',
    user: '******',
    database: '******',
    password: '******',
  })
  connection.connect()
  //const expenseTitle = req.body.body.expenseTitle
  const expenseTitle = req.body.expenseTitle
  connection.query("INSERT INTO book (title, summary) values (?,'1000');", [expenseTitle], function (error, row, fields) {
    res.redirect('./')
  })
  connection.end()
})

module.exports = {
  path: '/books',
  handler: app,
}

Solution

The problem is your axios.post call. The second argument to axios.post is the data you want to send, not an options object. So what you’re sending is data with a headers property and a body property. (It looks like you’re used to using fetch.) Options are the third argument.

If you needed to give the header, it would be like this:

axios.post("books/books/add", formData, {
    headers: {
        "Content-Type": "application/json"
    },
})
// ...

…but you don’t, jonrsharpe tells me that by default axios will stringify the object and send the appropriate header, so:

axios.post("books/books/add", formData)
// ...

You should also have a .catch after the .then to handle errors, since you’re not returning the promise from .then.

Leave a Reply

(*) Required, Your email will not be published