【问题标题】:post request not working, claims body data is not present when it is发布请求不起作用,声称正文数据不存在
【发布时间】:2021-08-29 20:29:31
【问题描述】:

我正在尝试用 prisma 中的新行更新我的表,但我似乎找不到问题所在。

我的帖子是这样的:

app.post(`/content`, async (req, res) => {
  const result = await prisma.content.create({
    data: {
      title: req.body.title,
      content: req.body.content,
    },
  })
  res.json(result)
})

我的模型如下所示:

model content {
  id        Int      @id @default(autoincrement())
  title String
  content String
}

我这样称呼我的帖子:

createContent() {
  let identifier = this.content.length + 1
  let newContent = { data: { id: identifier, title: 'Sample tekst', content: "Sample tekst" } }
  this.addContent(newContent.data)
      
  fetch('http://localhost:3000/api/content', {
    method: 'post',
    body: JSON.stringify(newContent)
  })

  .catch(error => {
    console.error('Error:', error)
  })
}

我尝试将id: req.body.id 添加到我帖子中的数据对象,但没有任何作用。

还尝试从 newContent 对象中删除 id,仍然是同样的错误。

我得到的错误是:

ERROR                                                                                                                                                       20:44:23
Invalid `prisma.content.create()` invocation:

{
  data: {
    id: undefined,
+   title: String,
+   content: String
  }
}

Argument title for data.title is missing.
Argument content for data.content is missing.

Note: Lines with + are required

【问题讨论】:

  • 在你的post方法中不应该是title: req.body.data.title吗?
  • 试过了,现在我的控制台说:错误无法读取未定义的属性“标题”,不确定这是否是进度
  • 首先,console.log() 不管request 你在app.post('/content', async (req, res) =>{})... 进入req,我也可以在createContent() 中看到你正在设置一个id,但是你的primsa id 变量设置为 @default(autoincrement()),这意味着它是自动创建和递增的。请参阅'Defining attributes' 标签下的'Defining a default value' 中的this documentation
  • 控制台日志记录 req 的结果太大而无法分享,所以我制作了一个视频:loom.com/share/57bba533953149899852e925a3752245 我在 createContent 中使用的 id 没有被帖子使用,因为就像你说的那样,虽然没有必要我的商店需要它才能将新对象推送到数组中,这就是我添加它的原因。我尝试在我的帖子中添加 id 并从给定对象中删除 id 但似乎两者都没有产生差异,控制台中显示了相同的错误。

标签: javascript vue.js express nuxt.js prisma


【解决方案1】:

我已经解决了这个问题。有两种方法可以解决此问题。

解决方案 1: 添加标题。

fetch('http://localhost:3000/api/content', {
  method: 'post',
  body: JSON.stringify(newContent),
  headers: { 'Content-type': 'application/json; charset=UTF-8' }
})

解决方案 2:

npm i axios安装axios,像一个真人一样,然后导入它,然后你的帖子如下:

axios.post('http://localhost:3000/api/products', newProduct)
  .then((response) => {
  console.log(response)
})
  .catch((error) => {
  console.log(error);
})

【讨论】:

    猜你喜欢
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多