DEV Community

Discussion on: Adding an API and database to your Nuxt App with Prisma

Collapse
ruheni profile image
Ruheni Alex Author

Hi Prashant 👋🏽

You can use the fetch, axios or http nuxt modules to fetch call the API in either your component or page as follows:

export default {
  data: () => ({
    posts: [],
  }),
  async fetch() {
    this.posts = await this.$http.$get("/posts");
  },
};
Enter fullscreen mode Exit fullscreen mode

You can choose how you would like to display your data in the view.

Collapse
rawalprashant profile image
Prashant Raval

Hi Alex,

Thanks for your response, well the thing is i am starting with Nuxt 3 so later i don't have to rewrite my project, and nuxt 3 have no support for axios.

Nuxt 3 having fetch option and h3, but i am not sure how to use them as Post method to submit my form data.

So do you have any idea about that?

Regards,

Thread Thread
ruheni profile image
Ruheni Alex Author

For a form submission, you can still use fetch to submit data to the API route.

We created a rest-nuxtjs example but it uses Nuxt v2 and a custom server. In that example, the create.vue page makes a form submission to an API route. You can use this example for inspiration when handling form submission in your application.

Here's what the function resembles:

export default {
  data() {
    return { title: '', authorEmail: '', content: '' }
  },
  methods: {
    createDraft: async function (e) {
      e.preventDefault()
      const body = {
        title: this.title,
        authorEmail: this.authorEmail,
        content: this.content,
      }
      try {
        const res = await fetch(`/api/post`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(body),
        })
        const data = await res.json()
        await this.$router.push({ name: 'drafts' })
      } catch (error) {
        console.error(error)
      }
    },
  },
}
Enter fullscreen mode Exit fullscreen mode

Let me know if you run into any other issues. I'd be happy to help! 🙂

Thread Thread
rawalprashant profile image
Prashant Raval

Hello Alex,

Before i test your example code for form submission, i am stuck with the API call, i have created a file server/api/index.js and here its code part


import express from 'express'
import pkg from '@prisma/client';
const { PrismaClient } = pkg;

const prisma = new PrismaClient({
    log: ['query']
})

const app = express()

// Body parser, to access `req.body`
app.use(express.json())

app.get('/apitest', async (req, res) => {
    res.end('Test API!')
})

app.post('/sendMessage', async (req, res) => {
    const { name, email, company_name, phone, message } = req.body
    const post = await prisma.contact.create({
        data: {
            name,
            email,
            company_name,
            phone,
            message
        }
    })
    res.status(200).json(post)
})

Enter fullscreen mode Exit fullscreen mode

Now, when i run the server localhost:3000 it says handle is not a function
with error code 500

i think as per nuxt 3 document for API ( v3.nuxtjs.org/docs/directory-struc... ) might be it has its own way to handle the request,

So, did you have ever tried this kind of call and have any suggestion for me to fix it?

Thanks a lot