Home » Php » php – How do I pre-render Nuxt.js API routes on the server side

php – How do I pre-render Nuxt.js API routes on the server side

Posted by: admin February 25, 2020 Leave a comment

Questions:

For Search Engine Optimization, I’m looking for a way to pre-render dynamic Nuxt.js route pages through an existing API.

I have tried using the asyncData() function to pre-render the results of my API on the server side, but when inspecting the source code, this is not working properly.

Situation

To make things more clear:

  • I use a third-party API to fetch metadata of a single book
  • Using dynamic Nuxt.js routes, I would like to pre-render the result on my server, for SEO reasons (for example, http://my-website.com/api/single-book/[ISBN_HERE]
  • I want Google and other search engines to crawl the website for each matched query

Edit: example code as requested
Dynamic route (.vue)

<template>
  <div>
      <h2>
          Load books by ISBN (currently requesting)
      </h2>

      <ul>
          <li v-for="(product, i) in products" :key="i">
              <b>(#{{product.id}})</b> {{product.title}}
              <br>
              {{product.shortDescription}}
          </li>
      </ul>
  </div>
</template>

<script>
export default {
    async asyncData({ params, $axios }) {
        // get the requested isbn from the params.
        let query = params.isbn;
        // api url
        let url = `http://bookfrontapi.test/bol-api/?q=${query}`;
        
        // make the request asynchronously
        const res = await $axios.get(url);
        // fetch the results
        const data = res.data;

        const products = data.products;

        return {
            products
        }
    }
}
</script>

<style>

</style>
How to&Answers: