Encountered 500 (RuntimeError) error while re-fetching data: problem solution for axios and nuxtjs
<p>I built a blog-based page using WordPress as API and Nuxt.js as JavaScript framework.
The problem occurs in my _slug.vue file. When I navigate to an individual blog (project) page, the individual blog posts render fine. However, if I reload a single blog post page, or just enter in the URL, the console shows the error: GET <em>url</em> 500 (RuntimeError). </p>
<pre class="brush:php;toolbar:false;"><template>
<div class="single-project">
<Header />
<h1>{{project.title.rendered}}</h1>
<article v-html="project.content.rendered"></article>
<ClickToAction />
</div></pre>
<pre class="brush:php;toolbar:false;"><script>
/* eslint-disable */
import axios from 'axios'
export default{
data() {
return {
project: {}
}
},
async asyncData({params}){
return await axios.get('https://my-api.wp/wp-json/wp/v2/project/' params.id)
.then((res) => {
return {
project: res.data
}
}).catch(function (error) {
if (error.response) {
// Request made and server responded
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
});
}
}
</script></pre>
<p>以及一个项目的链接:</p>
<pre class="brush:php;toolbar:false;"><nuxt-link :class="'item ' project._embedded['wp:term'][0].map(el => el.name.toLowerCase()).join(' ')" v-for="project in projects" :key="project.id" :to="{name: 'projekte-slug', params: { slug: project.slug, id: project.id}}"></pre>
<p>目标在nuxt.config.js中是静态的。</p>
<h1><strong>编辑</strong></h1>
<p>经过研究,我发现在nuxt-link的params对象中传递的id在重新加载后丢失,因为它需要“父”页面来获取id的值。为了解决这个问题,我通过API使用slug获取了项目,并显示了所有属性(例如标题、内容等)</p>
<pre class="brush:php;toolbar:false;">async asyncData({ params, $axios }) {
try {
console.log(params.slug);
const project = await $axios.$get(`https://my-api.wp/wp-json/wp/v2/project?slug=${params.slug}&_embed`)
return { project }
} catch (error) {
...
}</pre></p>