A script error occurs exclusively on dynamic routing in a static web page generated by NUXT

Currently working on a Nuxt.js website and encountering an issue. Initially, nuxt.config.js was set up as below to enable a headless CMS.

export default {
  target: "static",
  ssr: true,
  generate: {
    async routes() {
      const pages = await axios
        .get(
          `https://path/to/endpint`,
          {
            headers: { "XXXX-API-KEY": process.env.API_KEY },
          }
        )
        .then((res) =>
          res.data.contents.map((content) => ({
            route: `/${content.id}`,
            payload: content,
          }))
        );
      return pages;
    },
  },

    //other settings omitted

Next, a page was created at "/pages/_id/index.vue" with the following code:

<template>
  <div class="article">
    <p>{{ content.title }}</p>
  </div>
</template>

<script>
export default {
  name: "",
  async asyncData({ payload }) {
    if (payload) {
      return {
        content: payload,
      };
    }
  },
};
</script>

Upon running "nuxt start" and previewing the page, although "content.title" is displayed successfully, a console error occurs stating "TypeError: Cannot read properties of undefined (reading 'title')". The behavior seems peculiar since nuxt generate should only create static-transpiled files, however this error suggests that a vue variable is being re-evaluated in the browser...

This same code placed on a static route like pages/preview/index.vue does not trigger the error. Any insights or solutions would be greatly appreciated.

Answer №1

Figured it out on my own.

In nuxt.config.js, the correct format should be as follows:

res.data.contents.map((content) => ({
  route: `/${content.id}`,
  payload: content,
}))

I initially missed adding a slash in the "route" section of my code:

res.data.contents.map((content) => ({
  route: `${content.id}`,
  payload: content,
}))

I haven't grasped the difference yet, but I managed to resolve it anyway...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is a functional component in defineSlots?

With the latest version of Vue SFC (3.3+), slot scope has become type safe with the introduction of defineSlots. Is there a way to achieve the same type safety for slots in functional components as well? export default defineComponent({ name: 'MyCompo ...

Can someone provide a list of events for the .on function in Vanilla NodeJS?

Currently experimenting with NodeJS by testing basic backend functionalities like sending various HTTP requests from my index.html file to the server.js file. I plan to delve into Express soon. I've noticed a lack of documentation on NodeJS 'eve ...

The issue of CSS not being applied to HTML content after being inserted via AJAX has been encountered

I've successfully implemented AJAX to retrieve specific page content from a database, but now I'm facing an issue: When it comes to the 'Contact' page, the form retrieved from the database (as HTML) is not applying the CSS styles I hav ...

JavaScript is claiming that my class method is invalid, despite the fact that it is obviously a valid function

Implementing a genetic algorithm using node has been my latest challenge. After browsing through the existing questions on this topic, I couldn't find anything relevant to my issue. The problem arises when I attempt to call the determine_fitness metho ...

Showing and hiding nested Form Group validation in Angular 4 is a crucial feature that can improve

I have been exploring Angular 4 validation recently. Currently, I am working with a reactive form that contains two radio buttons and two form groups. The behavior I'm trying to achieve is when the user selects the first radio button, it removes valid ...

Entwine words around an immovable partition

Is it possible to create an HTML element that remains fixed in place even as the content on the webpage changes, with everything else adjusting around it? I am looking to add a continuous line that spans across a dynamic webpage. No matter how much conten ...

After being redirected from another page using history() in React, the state is initially set to null but later gets updated to the correct value - Firebase integration

After logging in and being redirected to the profile page, I encounter an error that says 'Unhandled Rejection (TypeError): Cannot read property 'email' of null'. How can I ensure that the state is set before proceeding with any additio ...

Exploring the differences between UTC and non-UTC date formats in Javascript

When working with JavaScript, I encountered a challenge in comparing two dates that are formatted differently. Specifically: 2015-09-30T00:00:00 and 9/30/2015 12:00:00 AM The former is in UTC format while the latter is not. Despite referring to the same ...

How can you optimize the storage of keys in JS objects?

Just pondering over this scenario: Consider a line definition like the one below, where start and end are both points. let ln = { s: {x:0, y:0}, e: {x:0, y:0}, o: 'vertical' } Now imagine having a vast array of lines, how can we sav ...

How can I implement a search box on my HTML website without relying on Google Custom Search?

Greetings to all! I am currently managing a website filled with HTML content. I am looking to incorporate a search box into the site. After researching on Google, most of the results point towards using Google Custom Search. However, I require a search box ...

When using Vue.js, it is not possible to quote variables in HTML element attributes

Below is the provided code snippet: <tr v-for="(item, index) in detail" :key="item.name" class="[[ item.name ]]"> <td>[[ index + 1 ]]</td> <td>[[ item.name ]]</td> The resulting HTML output i ...

The project is throwing an error: Unable to locate module './lib/md5-hex' in Ember JS

I attempted the following steps: uninstalling md5-hex using npm with the command: npm uninstall md5-hex --save reinstalling md5-hex using npm with the command: npm install md5-hex --save After performing these actions, I ran ember s but unfortunately, i ...

Having difficulty retrieving data despite providing the correct URL

I am encountering an issue with a fetch function designed to retrieve a JSON web token. Despite verifying the correctness of the URL, the function is not functioning as expected. Below is the front-end function: const handleSubmit = async (e) => { ...

Mongoose encountered an error when attempting to cast the value "......" as an ObjectId in the "author" path. The error was caused by a BSONError

I'm currently facing an issue with Mongoose in my NextJS project. Specifically, I am encountering a problem when trying to save a document where one of the fields references an ObjectId. The error message I receive is as follows: Cast to ObjectId fail ...

Employing JavaScript to insert a JSON value as a parameter in an HTML element's attribute

In a JSON file, I have "img" properties with .jpg file paths as their values (e.g "images/image.jpg"). I am attempting to insert these values into the 'src' attribute of existing HTML elements. Below are my attempts so far: I tried creating te ...

Sending a C# variable to an HTML file

I’m struggling to understand how I can use jQuery to access a variable from C# named sqlReq. My main objective is to be able to input my own SQL data into a PieChart. However, I’m unsure about how to call and define C# SQL requests in HTML or jQuery. ...

Using Jquery to automatically populate an input field if the user already exists

I'm currently working on populating a form if the user input for name and firstname already exists in my database. However, I am facing an issue with my JavaScript program where it fails to check if the name and firstname combination already exists i ...

Retrieve the toggle input value to change the page view using jQuery

I'm currently working on a web photo gallery project and I am looking to incorporate a toggle input button that allows users to switch between displaying albums or all photos. To achieve this, I need to extract the value of the input using jQuery and ...

utilizing jQuery to create dynamic data changes based on JSON file

<div id="rightside"> <h1>John Doe</h1> <p>1980 - 2020 <p><a href="johnswebsite.com">Visit Website</a> <p>Lorem ipsum dolor sit amet, consectetur adi ...

Testing a Vuetify Data Table using Jest for unit testing

I've developed a Vue.js application utilizing Vuetify and I'm currently working on unit testing a component that contains a Vuetify Data Table. The issue arises when trying to populate the table in my unit test, where Axios is mocked with Jest. ...