Issue with MIME handling while utilizing Vue-Router in combination with Express

Struggling to access a specific route in Express, I keep encountering an error in my browser. Additionally, when the Vue application is built, only the Home page and the 404 page seem to work properly, while the rest display a default empty HTML layout.

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

The Express code snippet causing the issue:

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

this.app.use(express.static(`${__dirname}/html`));
this.app.get('/*', (req, res) => res.sendFile(`${__dirname}/html/index.html`));

In the router.ts file in Vue, you can find this piece of code:

import { defineAsyncComponent } from "vue";
import { createRouter, createWebHistory } from "vue-router";

import Natives from '../views/Natives.vue';

const router = createRouter({
  routes: [
    {
      path: "/",
      name: "Home",
      component: defineAsyncComponent(() => import('../views/Home.vue')),
      meta: {
        name: "Home",
      },
    },
    {
      path: "/gta",
      name: "GTA V",
      component: defineAsyncComponent(() =>  import("../views/GTA.vue")),
      meta: {
        name: "GTA"
      }
    },
    {
      path: "/gta/natives",
      name: "Natives",
      component: Natives,
      meta: {
        name: "GTANatives",
      },
    },
    {
      path: '/gta/natives/:hash',
      name: 'Native',
      component: defineAsyncComponent(() =>  import("../views/DetailedNative.vue")),
      meta: {
        name: "DetailedNative"
      }
    },
    {
      path: "/:pathMatch(.*)*",
      name: "Page not found!",
      component: defineAsyncComponent(() =>  import("../views/NotFound.vue")),
      meta: {
        name: "NotFound",
      },
    },
  ],
  history: createWebHistory(),
});

Your assistance is greatly appreciated.

EDIT: After some investigation, it seems that the error occurs when there are more than two routes defined, such as /gta/native or /a/b, triggering the issue even if those pages do not exist. However, the exact cause remains elusive to me.

Answer №1

Through a stroke of luck, I managed to uncover the solution to my issue. It turns out that the root cause was a "corrupted" vite.config.ts file. By simply removing the line base: './', everything began functioning perfectly.

Answer №2

There appears to be no type mapping for the vue extension in the mime module.
You can refer to https://github.com/broofa/mime/tree/main/types

https://expressjs.com/en/4x/api.html#express.static
The express.static middleware supports the setHeaders option, allowing you to set the header manually.

const express = require('express')

const app = new express();
app.use(express.static(__dirname + '/public', {
    setHeaders: (res, path, stat) => {
        if (/\.vue/i.test(path))
            res.setHeader('Content-Type', 'application/javascript')
    }
}))
app.listen(55555, '0.0.0.0', () => {
    const http = require('http');
    http.get('http://127.0.0.1:55555/test.vue', res => console.log(res.headers['content-type']))
});

Test output

$ node app
application/javascript

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

Safari having trouble auto-playing Vimeo iframe embed

Update 6/26/23: Seems like a mysterious change occurred, as now the Vimeo video on project pages is playing automatically for me in Safari without any specific reason. It's working fine on Chrome too. Not sure if Vimeo made an update or if it's r ...

The quantity of documents queried does not align with the number of data counts retrieved from Firestore

Facing an issue with calculating the Firestore read count as it keeps increasing rapidly even with only around 15 user documents. The count surges by 100 with each page reload and sometimes increases on its own without any action from me. Could this be due ...

Creating grids and dividing them using a combination of CSS, JavaScript, and PHP

I've encountered an interesting challenge while working on a web project and would love some advice on how to tackle it: Within a database, I have a collection of images that I want to display in a grid format. The twist is that higher ranked images ...

Is there a way to extract the content from a dynamic textbox using a dynamic button in HTML and AJAX?

My current task involves fetching data from a database and updating the records individually. I have created a table with a text input field and a button that will be generated dynamically for each record. The text input field is populated with the previou ...

Console.log is not visible to jQuery's getJSON function

Currently, I am utilizing the getJSON method as shown below: $.getJSON("js/production-data.json").done(function(response) { console.log(response); console.log('hello'); }); While monitoring Firebug, the data retrieval process seems to ...

Tips on concealing a div until the value of a specific field surpasses zero

In order to ensure that users focus on the first section of the form before proceeding, I plan to hide the last section until a specific field has a value greater than zero. Check out my HTML code below: <div class="fieldcontainer"> <label>E- ...

The duration of time separating each individual post

After receiving approval for publish_actions on my app, I am currently attempting to comment on feed posts. Everything is functioning smoothly. Here is the code that is working: function home(token){ jQuery.ajax({ url:'https://graph.facebook.com ...

Tips for accessing a variable value within a JavaScript function

I am currently facing an issue where I am unable to retrieve a variable from a JavaScript function and use it outside of the function. While I can successfully output the variable value inside the function, I am struggling to access it elsewhere in my sc ...

Data has been successfully acquired through the query, however, it cannot be accessed via the GraphQL API

After successfully building the API with Apollo Server and verifying its functionality in GraphiQL, I proceeded to make requests to the API from a front-end React app using Apollo Client. const [getUserPosts, { loading, error, data }] = useLazyQuery(GET_US ...

Having an issue with eslint in combination with the vue/comment directive

Hey there, I was working on my website when suddenly I encountered 20 errors similar to this: Module Error (from ./node_modules/eslint-loader/dist/cjs.js): error clear vue/comment-directive Do you have any suggestions on how to solve this issue? ...

Challenges encountered while developing Angular FormArrays: Managing value changes, applying validators, and resolving checkbox deselection

I am facing an issue with my Angular formArray of checkboxes. In order to ensure that at least one checkbox is selected, I have implemented a validator. However, there are two problems that I need to address: Firstly, when the last checkbox is selecte ...

I encountered an issue when sending a PATCH request via Hoppscotch where the request body content was returned as 'undefined', although the username and ID were successfully

const express = require("express"); const app = express(); const path = require("path"); let port = 8080; const { v4: uuidv4 } = require('uuid'); app.use(express.urlencoded({extended: true})); app.set("views engine", ...

Upon utilizing @nuxtjs/auth for logging in, I noticed that it sends a request with a URL that deviates from the one I initially provided

The Issue at Hand Utilizing the Nuxt.js module @nuxtjs/auth' for login authentication has resulted in an unexpected error. Specifically, upon using the loginWith method, instead of redirecting to the URL specified in the configuration, it redirects t ...

Is there a more efficient method for iterating through this object?

Working with JSON and JS var data = { "countries": { "europe" : [{name: "England", abbr: "en"}, {name: "Spain", abbr: "es"}], "americas" : [{name: "United States"}], "asia" : [{name: "China"}] } }; JavaScript Loop for (k in data) { fo ...

Preventing AngularJs from Overriding VueJs Routes: Ensuring VueJs Routes Remain Uninterrupted

Currently, I am the steward of a substantial legacy ecommerce web application (constructed with AngularJS) and am in the process of completely reimagining it using VueJs. It is necessary for both applications to operate concurrently (until all existing fu ...

How to display a video with full height and width using CSS or JavaScript

I am trying to incorporate an html5 video (using the video tag) with 100% width and 100% height to play in the background. I have seen an example using an image, but I want to achieve the same effect with a video. Here is the code I have so far: #video { ...

Use AJAX to send a form submission along with an anchor tag

I've been facing a challenge trying to make this work, but unfortunately, I haven't had any success. Typically, all my forms include a submit input, and I handle AJAX submission in the following manner: <script> $("input#submit").click(fun ...

Getting a 406 (Not acceptable) error when trying to perform an AJAX action in Rails 4

I am attempting to automatically refresh a specific partial view every 60 seconds on the homepage. To make it easier to manage, I have divided the actions into two routes. However, I am encountering an issue with the respond_to block and could use some ass ...

Child component in Vue 2 not receiving defined props

After numerous attempts, I am still struggling to successfully pass a prop down to a child component. <Project :grossMarginPerResource="grossMarginPerResource" :threshold="threshold" :orderBy="orderBy" @refetch="refetc ...

Tips for transferring a JavaScript variable to PHP with AJAX

I am encountering an issue while trying to transfer a JavaScript variable, obtained from clicking a button, to PHP in order to execute a MySQL query. Here is my code: function ajaxCall(nodeID) { $.ajax({ type: "POST", url: "tree.php", data: {activeNode ...