Marnix Elling
Marnix Elling

Reputation: 389

post request not working, claims body data is not present when it is

I am trying to update my table with a new row in prisma and i cant seem to find what the problem is.

my post looks like this:

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

My model looks like this:

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

I call my post like this:

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

I tried adding id: req.body.id to the data object in my post but it didnt make a difference.

Also tried removing id from the newContent object, still same error.

The error i get is:

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

Upvotes: 0

Views: 2265

Answers (1)

Marnix Elling
Marnix Elling

Reputation: 389

I've fixed the problem. There's 2 ways of fixing this.

Solution 1: Add headers.

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

Solution 2:

Install axios with npm i axios,like a real man then import it and make your post as following:

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

Upvotes: 1

Related Questions