Navigating with Express and Vue

Currently, I am working on a basic web page that has an index '/' and a 404 page to handle errors at '/404'.

In my express app setup, I have the following configuration:

// Entry Point
app.use("/", express.static(resolve(__dirname, "client/dist")));

Furthermore, this is how I have defined my router in Vue:

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home,
    },
    {
        path: '/404',
        name: 'PageNotFound',
        component: () => import('../components/modules/PageNotFound'),
    },
    {
        path: '*',
        redirect: '/404',
    },
];

const router = new VueRouter({
    mode: 'history',
    base: '/',
    routes,
});

When I access my client-side application and navigate to a non-existent route like '/13eo31be', it correctly redirects me to '/404' using Vue's router. However, when I build my Vue app and run it through my server (which mimics how websites operate), here are the issues I encounter:

  • '/' => '/'
  • '/404' => cannot get /404 - should lead to '/404'
  • '/2323f2f' => cannot get /2323f2f - should also redirect to '/404'

I am seeking advice on how to configure express to pass the redirection responsibilities to the Vue Router seamlessly.

Answer №1

Forget about it, the problem was actually quite simple.

All I needed to do was route '/404' to the same index file as '/'.

app.use("/404", express.static(config.path));

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

Unable to successfully perform DELETE or UPDATE operations with Axios MySQL, encountering errors

I am currently working on a project that involves using Axios with Node.Js to perform a delete request in a MySQL table. However, I seem to be encountering an issue as I am not receiving any errors in the console despite having an error catch console.log s ...

Can anyone provide guidance on utilizing libraries within a Chrome extension?

I have been attempting to implement this for a total of 10 hours and I am struggling to make it work in script.js. // Creating a button element const button = document.createElement('button'); button.textContent = 'copy'; button.addEve ...

What steps can be taken to customize this code in order to develop a dictation application?

Currently, I have a code that functions by comparing two strings: str2 (which represents user input) and str1 (our reference string). The purpose is to determine whether any words in str2 are spelled correctly or incorrectly. So far, the code works well. H ...

Find the string "s" within a div element aligned vertically, using Popper

Currently utilizing Popper from Material-UI <Popper id={"simplePopper"} open={true} style={{backgroundColor: 'red',opacity:'0.5',width:'100%',height:'100%'}}> <div style={{height:"100%", ...

Ways to bring in a Typescript Vue project to a Javascript Vue

I am trying to incorporate this Calendar component into my Javascript Vue 3 project. To achieve this, I have created a new component in my project named ProCalendar.vue and copied the code from the example found in App.vue. Additionally, I have added the n ...

Enhancing a validation form with the 'onblur' event handler

Exploring the realm of JavaScript, I find myself intrigued by the concept of creating a validation form that activates upon clicking out of the input field. Implementing various techniques to integrate this feature into an existing form has been both chall ...

Looking for a script that automatically swaps out a div at set intervals? You'll need to tweak it so that it only

I created a js script that dynamically changes the content of certain div elements at specified intervals. While I appreciate how it functions, I now need to modify it so that the script only executes once. Can someone help me achieve this? <script typ ...

What is the best way to match every request except for css, js, and image files in the Express

Playing with Node.js and Express. Currently, my code looks like this: app.get('*', function(req, res) { }); I want to exclude static files such as .css, .js, and .png (or those that start with "css/", "js/", or "img/"). What's the most ef ...

What is the best way to assign a unique ID to every <td> element within a table using React Js?

Hello everyone. I am currently working on assigning unique ids to each td in a table based on data received through an API. This is what my code looks like so far. CodeSandbox const assignIdsToTableData = (data) => { var items = Object.values(data)[0 ...

While attempting to retrieve cookies, an error occurs stating: "TypeError: Cannot read property 'token' of undefined"

I've successfully generated a JWT token using the following code: const jwt = require('jsonwebtoken'); const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const userSchema = new mongoose.Schema({ ...

Body-parser problem arises

My terminal is showing the result as undefined, even though I have set the content type to application/json. app.js const bodyParser = require('body-parser') app.use('/posts', postRoute) app.use(bodyParser.json()) models const PostSch ...

Adding images in ascending order according to the parent div's ID

If I have three different divs with unique IDs on a webpage <div id="product-id-001"></div> <div id="product-id-002"></div> <div id="product-id-003"></div> Is there a way to add image elements based on the ID of each d ...

Executing a function in HTML using VueJS: A step-by-step guide

As part of my programming lessons, I am tasked with developing a social network for a company. One key feature involves displaying the number of comments linked to a post (similar to Facebook). To retrieve the comments, I'm utilizing vueX to fetch a ...

Changing the key name for each element in an array using ng-repeat: a guide

In my current project, I have an array of objects that I am displaying in a table using the ng-repeat directive. <table> <thead> <tr> <th ng-repeat="col in columnHeaders">{{col}}</th> //['Name&apo ...

Click on the link within the Checkbox label on MUI

I am working on creating a checkbox for the "Terms of Use," using FormControlLabel to nest a Checkbox. However, I also need to include a link that opens a Dialog component displaying the terms. The challenge is that clicking on the link checks the checkbox ...

Issue with Knockout.js: Parsing error in bindings - SyntaxError: Unexpected token `};`

Take a look at this example. I've tried to simplify it as much as possible, but I'm still struggling to figure out where I went wrong. Any help would be greatly appreciated )) P.S Stack Overflow requires code, not just a link to jsfiddle. H ...

Guarantee of SQL integration within JavaScript

I am trying to retrieve the value of the message variable, but all I see in the console is the following: result [object Promise] async function Testing() { let response = await new Promise((resolve, reject) => { db.query("SELECT * FROM `ni ...

Guidelines for retrieving a class name using jQuery when hovering over a div

I need assistance in fetching the class name by hovering over a div. Both divs have the same id but slightly different class names. Here is an example: <div id="1-someid" class="1-example-class border cz"> ...more elements go here.... </div> ...

Hold off until the script is successfully downloaded and executed, then patiently wait for the DOM to finish loading

I'm facing a challenge with running Javascript conditionally without it being in requirejs form. The script is located on the same server/domain as the requesting page, where an ajax call needs to be made. Is there a foolproof way to ensure that an a ...

Using TinyMCE editor to handle postbacks on an ASP.NET page

I came up with this code snippet to integrate TinyMCE (a JavaScript "richtext" editor) into an ASP page. The ASP page features a textbox named "art_content", which generates a ClientID like "ctl00_hold_selectionblock_art_content". One issue I encountered ...