NuxtJS Static generated HTML page fails to load JavaScript while accessing /index.html

I'm currently working on a project using Nuxt.js to generate static content, which involves utilizing JavaScript for tasks such as navigation and form functionality.

Everything works smoothly when running the page with npm run dev.

However, after exporting the content with npm run build && npm run generate and deploying it to my server (CDN specifically requested by the user, in this case Google Cloud Storage), I encounter an issue where accessing the page without the index.html suffix works perfectly fine.

For example:

Visiting functions correctly

but

Accessing doesn't work properly.

The page displays CSS and DOM elements, but the JavaScript functionalities are not operational. In the Google Chrome Dev-Tools, I noticed that although the JavaScript files appear to be loaded in both cases, they are not executed under the second scenario. Attached screenshots show similarities between the two situations.

https://i.stack.imgur.com/DpEFg.png

My Nuxt configuration is quite minimal in terms of render and build settings, with only resourceHints disabled. I suspect that the issue might be related to the router's handling of accepting only folders containing the index.html file. The router paths are dynamically generated through nuxtLinks.

Any suggestions or insights would be greatly appreciated?

Answer №1

Latest Update

After spending an additional 1-2 hours searching for solutions, I ultimately stumbled upon a resolution.

I discovered a technique to include the index.html suffix to the router as an alias for all paths.

By expanding the router within the nuxt-config file, it is possible to create an alias based on the router path. While this may not always be the ideal approach, it proved to be quite effective in this particular scenario.

router: {
  extendRoutes(routes) {
    routes.forEach((route) => {
      // When options.generate.subFolders is true (default)
      const alias =
        route.path.length > 1 ? `${route.path}/index.html` : '/index.html'
      // When options.generate.subFolders is false
      // const normalizedRoute = route.path.replace(/\/$/, '') // Remove trailing slashes if they exist
      // const alias =
      //   route.path.length > 1 ? `${normalizedRoute}.html` : '/index.html'
      route.alias = alias
    })
  }
}

This valuable snippet was sourced from a reddit post by animagnam (https://www.reddit.com/r/Nuxt/comments/gzwrqu/visiting_generated_site_routes_with_trailing/ftnylrt?utm_source=share&utm_medium=web2x&context=3) and has proven to function flawlessly in both production and testing environments.

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

How can I retrieve the current session's username when passport.js is returning a promise containing `{false}` for `req.user`?

While working in Node.js, I implemented the passportJS LocalStrategy to handle user authentication. One of the functionalities I used was req.getAuthenticated() This function allows me to check if the current session is authenticated. Next, I needed to r ...

Using Double Equal in a JavaScript For Loop

I'm struggling to comprehend why utilizing a double equals (or even a triple equals) in the condition of a for loop doesn't function as expected. Consider this example: for (i = 1; i == 5; i++){ console.log(i) } When I replace == with <= ...

Exploring the intricacies of Node-Craigslist syntax

Greetings! I am currently utilizing the node-craigslist package found at https://github.com/brozeph/node-craigslist and I am in need of assistance with some syntax related to the details method. The documentation provides the following example: client . ...

The output from the Compute function is not showing up in the TextBox as expected

I'm currently working on an HTML page that contains two textboxes and a button. I've created a Compute function to display the result in one of the textboxes, but unfortunately, it's not functioning as expected. No alerts are appearing on th ...

What is the appropriate HTTP status code for "item not found" when using RESTful ajax?

Imagine having a single-page web application featuring a list of items. Users can click on an item to view more information about it. The details of each item are loaded asynchronously via an AJAX GET request to the URL http://www.example.com/item/[id], an ...

Utilize React JS to dynamically render JSON array of images onto a JSX page in React

state = { products: [ { img: "'./images/heartstud.jpg'", name: "Heart Earrings", price: "1.99", total: "3.98", count: 2, description: "Yellow Chimes Crystals from Classic Designer Gold Plated Styl ...

The attribute 'selectionStart' is not a valid property for the type 'EventTarget'

I'm currently utilizing the selectionStart and selectionEnd properties to determine the beginning and ending points of a text selection. Check out the code here: https://codesandbox.io/s/busy-gareth-mr04o Nevertheless, I am facing difficulties in id ...

What could be causing my image not to show up on ReactJS?

I'm new to ReactJS and I am trying to display a simple image on my practice web app, but it's not showing up. I thought my code was correct, but apparently not. Below is the content of my index.html file: <!DOCTYPE html> <html> & ...

Using JQuery to trigger the onchange event for a select tag

I am working with jQuery where I need to append select tags inside a table for each row. I want to add an onChange event for each dropdown on every row. However, the approach I have taken doesn't seem to be working. This is what my jQuery code looks l ...

Sending documents to a printer directly from a Rails application

Is there a library or gem in Rails that can be used to print the contents of a web page directly onto paper? I am curious if it's possible to specify only a specific part of the page, such as a div, for printing. Any guidance, advice, or tutorial link ...

Attempted to fetch information using Ajax in Grails

I am attempting to utilize jQuery and ajax with the Grails framework to load the content registration page. However, upon loading the page, I am encountering an issue where the menu and registration fields are duplicated within the page. <script src ...

Including a cancel button to close the open window

var messagebox = Ext.widget("messagebox", { target: grid, progressMessage: "Loading" }); The message box displayed above indicates the loading progress bar that appears when the download button is clicked. I am looking to incorporate a cancel button i ...

What is the best way to retrieve an empty instance using a getter in Vuex?

My store has a default setting that returns undefined for a specific attribute: // store.js export const state = { locationLoading: false, locationsLoading: false, locations: [], location: undefined, <-- }; In my component, I am utiliz ...

Display Vue component based on a condition

I am currently working on rendering different components in the navbar based on the email/account that is signed in. There is a function called "getUser()" which retrieves the user's email. The items in the navbar include: Home, Procurement Site, Moni ...

Using Angular and Jade to pass an array from a controller to script tags

I am trying to figure out how to access an array in my controller and display it accurately within the <script> tags in my jade template. For instance: Controller.js $scope.myArray = ["item1","item2"]; Within my index.jade: script. var clien ...

When you reach a scrolling distance of over 300 vertical heights,

Is it possible to show and hide a class based on viewport height? I am familiar with displaying and hiding a class after a specified pixel height, but I'm wondering if it's achievable using viewport height instead? Specifically 3 times the viewp ...

Problem with javascript querystring code

Currently in the process of writing some vanilla JavaScript code to manipulate query strings without using jQuery. Here's what I have so far: // If there is no viewid in the query string, append it as a new key if (newUrl.indexOf("viewid") == -1) { ...

Can a Vue component in SFC form be utilized as a mixin?

Consider this scenario, where I have a component created in SFC format: // Parent.vue <template> <div> {{ txt }} </div> </template> <script> export default { name: 'ParentComponent', data() { return ...

Unlimited possibilities with parameters on an express server

I've set up React Router with recursive parameters, similar to the example here. On my Express server, I'm attempting to handle routes like /someRoute/:recursiveParameter? router.get('/someRoute/:recursiveParameter?', async (req, res ...

The error message encountered while using String.search("sinh(2"): "Regular expression is invalid."

Encountering an issue: var test = $("#k_w").val().search("sinh("+parseFloat(sinh_array[i])); An error message is displayed by the debugger: Uncaught SyntaxError: Invalid regular expression: /sinh(2/: Unterminated group. sinh_array[i] represents numerica ...