提问者:小点点

在nodejs中只接收带有对象标签的空数组


如果我从前端(Nuxt)发送一个数组到NodeJs,我只收到一个带有对象标签的空数组。这里有什么问题?我在用快递,人体解析器,穆特

数组示例:[{“content”:

安慰日志(请求正文)

[Object: null prototype] {
  postTitle: 'title',
  content: '[object Object],[object Object]'
}
exports.createBlogPost = async (req, res) => {
    console.log(req.body)
    try {
        const post = new BlogPost({
            postTitle: req.body.postTitle,
            content: req.body.content,
            mainImage: req.file
        })
        await post.save()

        if(post) {
            return res.status(200).json({
                success: true,
                message: 'Saved blog post successfully',
                post: post
            })
        }
    } catch(err) {
        console.log(err)
    }
}

Nuxt.js

async savePost() {
      const data = new FormData()
      data.append('postTitle', this.postTitle)
      data.append('content', this.array)
      data.append('mainImage', this.selectedFile, this.selectedFile.name)

      const blogPost = await this.$axios.$post('/api/create-blog-post', data)

      if (blogPost.success) {
        console.log(blogPost)
      }
    },

共1个答案

匿名用户

下面是我们可以通过FormData

在将数组附加到FormData并通过AJAX发送的注释中发现了这一点

for (let i = 0; i < array.length; i++) {
  const ItemInArr = array[i]
  for (const prop in ItemInArr) {
    data.append(`content[${i}][${prop}]`, ItemInArr[prop])
  }
}

Nuxt.js

async savePost() {
      const array = this.array
      const data = new FormData()
      data.append('postTitle', this.postTitle)
      data.append('mainImage', this.selectedFile, this.selectedFile.name)

      for (let i = 0; i < array.length; i++) {
        const ItemInArr = array[i]
        for (const prop in ItemInArr) {
          data.append(`content[${i}][${prop}]`, ItemInArr[prop])
        }
      }
      const blogPost = await this.$axios.$post('/api/create-blog-post', data)

      if (blogPost.success) {
        console.log(blogPost)
      }
    },