【问题标题】:I should get body from post request with req.body.item?我应该使用 req.body.item 从发布请求中获取正文?
【发布时间】:2021-07-12 03:47:19
【问题描述】:

我学习了如何在使用 express 时从 post 请求中获取正文数据。大多数示例代码表示req.body.item 应该能够获取我想要使用的值,例如将值插入到表中。

但我无法通过req.body.item 获得价值,但最终可以通过req.body.body.value 获得价值。我是否没有以正确的方式获取帖子正文值,或者这不是问题?

Node.js
  v14.15.4
Nuxt.js
  @ v2.15.4
Vue.js
  vue@2.6.12
Express
  ^4.17.1

(expense.vue),用正确的代码更新
将表单数据发布到“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),用正确的代码更新
将收到的帖子数据插入表中

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,
}

【问题讨论】:

  • axios.post 的第二个参数不是选项对象。

标签: javascript node.js vue.js express


【解决方案1】:

问题在于您的axios.post 电话。 axios.post 的第二个参数是您要发送的数据,而不是选项对象。所以你发送的是带有headers 属性和body 属性的data。 (看起来你习惯使用fetch。)选项是第三个​​参数。

如果你需要给标题,它会是这样的:

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

...但你没有,jonrsharpe tells me 默认情况下axios 将字符串化对象并发送适当的标头,所以:

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

您还应该在.then 之后有一个.catch 来处理错误,因为您没有返回来自.then 的承诺。

【讨论】:

  • @Crowder 谢谢你的回答。我刚刚编辑了我的代码,它正在工作!
【解决方案2】:
axios.post("books/books/add", formData, {
    headers: {
        "Content-Type": "application/json"
    },
})

【讨论】:

  • 查看其他答案。默认情况下,axios会将对象字符串化并设置header,所以header是不必要的。
  • 这会起作用,但最好包含一个解释您已更改的内容和原因,以及相关文档的链接。见How to Answer
  • 感谢您的回答!现在它工作正常。我什至可以删除 headers!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-12
  • 2016-06-21
  • 1970-01-01
  • 2023-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多