I'm grabbing blog posts from the Contentful API. I'd like to use a slug in my URL instead of an ID but can't seem to get it working. It works fine when just using an ID; however, when I try and use the slug and pass in the ID as a param, it fails (404).
🆗 working => myurl.com/post/12345
🆗 working (better) => myurl.com/post/my-awesome-slug?id=12345
🚫 not working (ideal) => myurl.com/post/my-awesome-slug
Expected results
Actual results
Data object
{
sys: {
id: some_id
},
fields: {
title: my_title,
content: my_content,
slug: my-slug
}
}
Meh. OK, but not ideal bc I don't want an ID to show up in the url.
pages/index.vue
<nuxt-link
:to="{ name: 'post-id', params: { id: sys.id } ">{{ fields.title }}
</nuxt-link>
pages/post/_id.vue
async asyncData ({ params }) {
let { data } = await axios.get(`https://cdn.contentful.com/spaces/[MY_SPACE_ID]/entries/${params.id}`, {
params: {
access_token: [MY_TOKEN]
}
})
return { post: data.fields }
},
head () {
return {
title: this.post.title
}
}
Better, but not an ideal solution b/c I don't want the id to show up in the url. myurl.com/my-slug?id=12345
pages/index.vue
<nuxt-link
:to="{ name: 'post-slug', params: { slug: fields.slug }, query: { id: sys.id }">{{ fields.title }}
</nuxt-link>
pages/post/_slug.vue
async asyncData ({ query }) {
let { data } = await axios.get(`https://cdn.contentful.com/spaces/[MY_SPACE_ID]/entries/${query.id}`, {
params: {
access_token: [MY_TOKEN]
}
})
return { post: data.fields }
},
head () {
return {
title: this.post.title
}
}
pages/index.vue
<nuxt-link
:to="{ name: 'post-slug', params: { id: sys.id, slug: fields.slug } }">{{ fields.title }}
</nuxt-link>
pages/post/_slug.vue
async asyncData ({ params }) {
let { data } = await axios.get(`https://cdn.contentful.com/spaces/[MY_SPACE_ID]/entries/${params.id}`, {
params: {
access_token: [MY_TOKEN]
}
})
return { post: data.fields }
},
head () {
return {
title: this.post.title
}
}
<!--cmty--><!--cmty_prevent_hook--><div align="right"><sub><em>This question is available on <a href="https://nuxtjs.cmty.io">Nuxt.js</a> community (<a href="https://nuxtjs.cmty.io/nuxt/nuxt.js/issues/c1327">#c1327</a>)</em></sub></div>