What could be causing the failure of the 404 view to appear when navigating to routes with parameters in this Vue 3 application?

Currently, I have been dedicating my time to developing a single page application using Vue 3, TypeScript, and integrating The Movie Database (TMDB) API.

My current focus is on creating a custom 404 error page for the application.

In the file src\router\index.ts, you will find the following code:

import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import TopRatedMoviesView from '../views/TopRatedMoviesView.vue';
import MovieDetailsView from '../views/MovieDetailsView.vue';
import ActorDetailsView from '../views/ActorDetailsView.vue';
import NotFoundView from '../views/NotFoundView.vue';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/top-rated',
    name: 'top_rated',
    component: TopRatedMoviesView
  },
  {
    path: '/movie/:id',
    name: 'movie_details',
    component: MovieDetailsView
  },
  {
    path: '/actor/:id',
    name: 'actor_details',
    component: ActorDetailsView
  },
  {
    path: '/:pathMatch(.*)*',
    name: "404",
    component: NotFoundView
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

Within the file src\views\NotFoundView.vue, this is the content:

<template>
  <div class="container d-flex">
   <div class="text-center">
      <h1 class="mb-3">404 | page not found</h1>
      <router-link class="btn btn-sm btn-success" to="/">
        <strong>Go to the Homepage</strong>
      </router-link>
   </div>
  </div>
</template>

<script lang="ts">
  import { defineComponent } from 'vue';

  export default defineComponent({
    name: 'NotFoundView',

  });
</script>

The expected behavior is that the 404 view should display when there is a random string after the root URL, like

http://localhost:8080/someNonExistingPath
.

However, an issue arises when providing an incorrect parameter to a dynamic route, as seen in

http://localhost:8080/movie/a615656
.

I am seeking guidance on troubleshooting this issue and implementing a more reliable solution. Any suggestions would be greatly appreciated.

Answer №1

One reason this issue may occur is when you navigate to the /movie/a615656 URL, which still matches the route parameter /movie/:id. This is because sometimes, the id can contain non-numeric characters.

To resolve this, you have two options: either use route REGEX to filter out non-numeric values or manually redirect to the 404 view.

For instance, in your getMovieDetails method, you could check for non-alphanumeric characters and redirect to the 404 view. However, this approach can be inconsistent as even if the id is valid, the corresponding item may not be available on the server side. So a better practice is to handle errors in the catch method, like so:

.catch((err) => {
    //log error
    console.log(err);
    //if the error status is 404
    if (err.response.status == 404) {
        router.push({ name: '404' })
    }
});

While this approach may introduce a slight delay due to waiting for the server response, it is the recommended way to handle such situations. In fact, Nuxt's documentation provides a similar example:

const route = useRoute()
const { data } = await useFetch(`/api/movies/${route.params.slug}`)
if (!data.value) {
  throw createError({ statusCode: 404, statusMessage: 'Page Not Found' })
}

This code snippet serves as an illustration, so there's no need to be concerned if you're unfamiliar with NuxtJS.

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

Ways to apply the .not selector efficiently in jQuery

I have a situation with two separate divs, one named task1 and the other named task2. Each of these tasks contains panels with various names. Within task2, there is a duplicate name (Greg), who also belongs to the duplicate class. I'm trying to figure ...

Encountering Error 500 with Jquery Min.Map File

ERROR: GET request to http://domain.com/assets/js/jquery-1.10.2.min.map returned a 500 Internal Server Error Can anyone help me figure out what's causing this error? I checked the log files in /var/log/error but couldn't find any information. T ...

Utilize $.ajax to gracefully wait for completion without causing the UI to freeze

Consider a scenario where there is a JavaScript function that returns a boolean value: function UpdateUserInSession(target, user) { var data = { "jsonUser": JSON.stringify(user) }; $.ajax({ type: "POST", url: target, data: ...

Changing the designated materialUI class

Within the project, I am utilizing this theme: export const theme = createMuiTheme({ ...defaultThemeConfig, overrides: { ...defaultThemeConfig.overrides, MuiListItem: { root: { '&:nth-child(odd)': { backgro ...

How can I correct the error in accessing state data with a getter and displaying the outcome in a component?

I am relatively new to vuejs 3 and vuex 4. I'm currently attempting to create a simple getter, but when it didn't work as expected, I resorted to using console.log to check the output. The result that appeared in the console was: ComputedRefImpl ...

Select a filter first before uploading your image

Here I have a script that allows users to select a folder. My question is how can I modify the script so that once they have chosen a folder, the script will send the picture to a PHP script for uploading to the server? $(function() { /* Th ...

Cross-domain scripting

I have a unique javascript code hosted on my server. I want to offer website visitors a similar implementation approach to Google Analytics where they can easily embed the script on their servers. For instance: <script type="text/javascript" src="http: ...

Attempting to modify the environmental variable within node.js via the terminal proves to be a fruitless endeavor as the value consistently remains undefined

Recently, I entered the world of backend development and came across this JS code utilizing express: const express = require('express'); const app = express(); const port = process.env.PORT || '3000'; app.listen(port, ()=> console.lo ...

Variables for NPM Configuration

After researching the best way to securely store sensitive information, I decided to utilize the config package and environment variables for added security. Here is how I implemented this setup: Created a config directory containing two files: default.js ...

Issue with Material UI scrollable tabs failing to render properly in Internet Explorer

Currently, we are integrating Material UI into our tab control for our React Web UI. Everything is functioning smoothly in Chrome, but when we attempted to test it in IE, the page failed to load and presented the error below: Unhandled promise rejection ...

What is the best way to generate a dynamic HTML table using Angular 6?

I need to display an array of 100 items in an HTML table with 10 rows and 10 columns. How can I achieve this using Angular? tableIndexTR = []; tableIndexTD = []; constructor(private data: TransferService) {} ngOnInit() { for (let _i = 1; _i <= ...

Generate a division element within an HTML page by invoking a function in Angular version 2

Currently, I have a list of orders displayed in a view. When clicking on the order id for a specific order in the list, my goal is to expand and show more detailed information about that particular order. To accomplish this, I've created an order view ...

What is the best way to define a typescript interface as a class property?

Here is an example of how I have defined an interface: export interface Donor{ donorName: string; donorId: string; donorPassword:string donorAge: number fitnessReport: string physicianApproval: string } In the following class, I w ...

What is the process for eliminating required validators from an Angular input field?

After working with Angular 13 in my application, I encountered a scenario where I needed to remove a required field validation based on value changes. You can check out this stackblitz for a demo of what I'm trying to accomplish. In the demo, at leas ...

get an array of JSON data from a VueJS fetch or axios.get request

I can't seem to figure out this issue. The code I have below is giving me some trouble. When I try to run it, I keep getting the following error message: Access to XMLHttpRequest at 'URL' from origin 'http://localhost:8000' has b ...

Vue.js fails to display multiple uploaded images

I have been working on implementing a multiple image upload feature using vue.js. So far, everything seems to be functioning correctly. However, I am facing an issue where the HTML does not display thumbnails of the images I have selected. Additionally, I ...

a:hover CSS style altering the behavior of buttons with images in a web browser

Earlier I attempted to ask this question from my phone, but it ended up being overly convoluted and confusing. Therefore, I have decided to start fresh after locating a working PC. Unfortunately, due to the sensitive nature of the project, I am unable to p ...

Executing a series of functions in succession using jQuery

I am trying to iterate through an object that contains functions which need to execute consecutively. Ideally, I would like these functions to be chained together in a way where one function waits for the previous one to finish before executing (e.g., func ...

Finding the index of a class using jQuery is posing some difficulties

I am facing a challenge with controlling multiple hidden modals on a webpage using a single block of JavaScript code. In my attempt to test whether I can access the correct close button with the class close, I am encountering an issue where my console.log ...

PostgreSQL dynamic query with Node.js

I am currently developing a note-taking app using REACT. My focus is on tracking only the changes made by the user to the note, rather than the current state of the note. For properties that have not been altered, I intend to send them as an empty string ...