简体   繁体   English

我应该使用 req.body.item 从发布请求中获取正文?

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

I learned how to get body data from post request when using express.我学习了如何在使用 express 时从 post 请求中获取正文数据。 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.大多数示例代码表示req.body.item应该能够获取我想要使用的值,例如,将值插入到表中。

But I couldn't get the value with req.body.item but could finally get it with req.body.body.value .但我无法通过req.body.item获得价值,但最终可以通过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
  vue@2.6.12
Express
  ^4.17.1

(expense.vue), Updated with correct code (expense.vue),用正确的代码更新
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 (books.js),用正确的代码更新
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,
}

The problem is your axios.post call.问题是您的axios.post电话。 The second argument to axios.post is the data you want to send, not an options object. axios.post的第二个参数是您要发送的数据,而不是选项 object。 So what you're sending is data with a headers property and a body property.所以你发送的是带有headers属性和body属性的数据 (It looks like you're used to using fetch .) Options are the third argument. (看起来您已经习惯使用fetch了。)选项是第三个参数。

If you needed to give the header, it would be like this:如果你需要给 header,它会是这样的:

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: ...但你不知道, jonrsharpe 告诉我,默认情况下axios将字符串化 object 并发送适当的 header,所以:

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 .您还应该在.catch之后有一个.then来处理错误,因为您没有从 .then 返回.then

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM