Connect Directus and Nuxt 3
First let's create a custom API Route to fetch items from Directus server/api/directus.ts
.
In this file we simply calling the directus server and rewrite parameters of original requests.
export default async (req, res) => {
const newUrl = req.url.replace(/\?directusUrl=/, '')
const dta = await $fetch('http://localhost:8055' + newUrl)
return {
data: dta
}
}
after that, we are able to make requests on the route /api/directus
.
Now create a composable function to simplify calls composables/fectus.ts
import { useRuntimeConfig } from '#app'
export default async function (url: string) {
const { data } = await useFetch('/api/directus', {params: {directusUrl: url}})
return data._value.data.data
}
The request in our pages would be then:
const blogposts = await fectus('/items/blog')
or if we would like to use a filter, we include it into url
const blogposts = await fectus('/items/blog?filter[title][_eq]=' + route.params.title)