Encountering Error with Axios in Nuxt while Navigating Pages

Working on a nuxt application utilizing axios for API calls. In my index.vue file, I have the code snippet below.

<template>
  <div>
    <Hero />
    <Homebooks :details="details" />
  </div>
</template>

<script>
export default {

  // USING ASYNC AWAIT
  async asyncData ({ $axios, error }) {
    try {
      const details = await $axios.$get('http://127.0.0.1:8001/api/books')
      return { details }
    } catch (e) {
      error({
        statusCode: 503,
        mesage: 'Unable to fetch'
      })
    }
  }

  // USING PROMISES
  // asyncData ({ $axios, error }) {
  //   return $axios.$get('http://127.0.0.1:8001/api/books').then((response) => {
  //     return { details: response }
  //   }).catch((e) => {
  //     error({
  //       statusCode: 503,
  //       message: 'Unable to fetch data'
  //     })
  //   })
  // }
}
</script>

Encountering an issue when navigating back to this page using the menu after visiting another page. The following error is displayed:

Unable to fetch event An error occurred while rendering the page. Check the developer tools console for details.

However, upon page refresh, the data reloads without error. Unclear on what might be causing this problem.

Answer №1

Within the config/cors.php file, implement the following:

'paths' => ['api/*'] 

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

Node and browser compatible JavaScript logging library for effective logging experience across platforms

Our team is utilizing Visionmedias debug library, as it seamlessly functions on both browsers and Node.js environments. We are in search of a more reliable alternative to debug that offers the same level of functionality (error, warn, info, etc) for both ...

Designing a nested function within a function encapsulated within a class

Suppose I have a class with a function inside: var myClass = class MyClass() { constructor() {} myFunction(myObj) { function innerFunction() { return JSON.stringify(myObj, null, 2); } return myObj; } } In this scenario, callin ...

No children were located within the div element

Presently, I am attempting to disable an image for the initial element in each faqs div class in HTML. To achieve this, I am aiming to target the parent element of faqs and then navigate downwards to locate the initial list element using the following Java ...

Difficulty in toggling the visibility of the react-date-range picker package when selecting a date

I need assistance with a problem I'm facing. I am having trouble hiding and showing the react-date-range picker upon date selection. The issue is related to a package that I am using for date range selection. You can find the package link here - https ...

Single-select components in React Native

I am currently working on implementing a simple single selectable item feature, illustrated in the image provided below. https://i.stack.imgur.com/U2rJd.png At this moment, I have set up an array containing my data items and utilized the .map function to ...

I possess a certain input and am seeking a new and distinct output

I am looking to insert a word into an <input> and see an altered output. For example, Input = Michael Output = From Michael Jordan function modifyOutput() { var inputWord = document.getElementById("inputField").value; var outputText = "print ...

async.series: flexible number of functions

Hello everyone, I'm currently working with Node.js (Express) and MongoDB (mongooseJS). My goal is to create a series of async functions that query the database in the right order. Here is my question: How do I go about creating a variable number of a ...

Explore the functionality of the Enter key and search button with JavaScript

I have the following code that works perfectly when I click on the search button. However, I would like to know how I can also initiate a search using the enter key. Here is the code snippet: <script> function mySearch() { var text = document.g ...

Is it feasible to save BoxGeometries or MeshLambertMaterial in an array using Three.js?

var taCubeGeometryArray = new Array(); var taCubeMaterialArray = new Array(); taCubeGeometryArray.push(new THREE.BoxGeometry( .5, .5, .5)); taCubeMaterialArray.push(new THREE.MeshLambertMaterial({map: THREE.ImageUtils.loadTexture( "image.png" )})); Could ...

How to troubleshoot NodeJS errors when piping data from tar packing to webhdfs

I am currently in the process of developing a node application that utilizes Hadoop as a long-term storage solution for data when one of my services is not operational. To optimize efficiency and minimize processing time due to anticipated high transfer vo ...

How can I assign a prop to a component within the root layout in Next.js version 13, especially when the root layout is required to be a server-side component at all times?

I need assistance with a project I'm working on. My goal is to create a SongPlayer component in Next.js version 13 that plays music and is positioned at the bottom of the window, similar to Spotify's player. However, my SongPlayer component requi ...

Importing TypeScript Modules from a Custom Path without Using Relative Paths

If we consider the following directory structure: - functions - functionOne - tsconfig.json - index.ts - package.json - node_modules - layers - layerOne - tsonfig.json - index.ts - index.js (compiled index.ts ...

Send the user to a specified destination

Currently, I am working on creating a form that allows users to input a location and have the page redirect to that location after submission. However, I am facing difficulty in determining how to set the value for action="" when I do not know what the loc ...

A step-by-step guide on making a web API request to propublica.org using an Angular service

Currently, I am attempting to extract data from propublica.org's congress api using an Angular 8 service. Despite being new to making Http calls to an external web api, I am facing challenges in comprehending the documentation available at this link: ...

What is the best way to define a variable within a function?

Here's a function designed to verify if the username has admin privileges: module.exports = { checkAdmin: function(username){ var _this = this; var admin = null; sql.execute(sql.format('SELECT * FROM tbl_admins'), (err, result, fields ...

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 ...

Clicking 'Submit' triggers a continuous loop upon loading

I set up this form to automatically submit once the page has finished loading. However, I seem to be encountering a problem where the page gets stuck in a continuous loop of reloading. HTML <body onload="document.getElementById('filters').su ...

After manipulating the array, Vue fails to render the input fields generated by the v-for directive

After setting the value externally, Vue component won't re-render array items. The state changes but v-for element does not reflect these changes. I have a component that displays items from an array. There are buttons to adjust the array length - &a ...

Guide on combining vendor CSS files in a React application using Webpack

Incorporating third-party libraries is an essential part of my project. For example, I have Mapbox GL installed via npm, which comes with CSS files needed for its functionality. The Mapbox GL CSS file can be found at mapbox-gl/dist/mapbox-gl.css in the no ...

Issue with Vue.js: Difficulty sending an array of values to an endpoint

I am currently in the process of learning Vue in order to complete my project, which has a Java Spring backend. The endpoint I am working with expects an object with the following values: LocalDate date; Long buyerId; Long supplierId; List<OrderDetails ...