Issue with Vue.js: routes are not found upon page refresh

Here is a basic vue-routing example:


const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }

const routes = [
    { path: '/foo', component: Foo },
    { path: '/bar', component: Bar }
];
const router = new VueRouter({
    routes:routes,
    mode: 'history'
});

var app = new Vue({
    router,
    data: {
        message: 'Hello Vue!'
    },
    mounted:function(){

    }
}).$mount('#app');

In HTML


<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
<router-view></router-view>

The links work properly (e.g. : /foo and /bar) when clicked, but if I refresh any vue-routed URL (e.g. /foo or /bar), I receive an error message:

Cannot get the page

I am serving it with a simple Express server


app.get('/', (req, res) => res.sendFile('index.html',{ root : __dirname}))

Answer №1

To ensure all routes redirect to the main file index.html, use the following code:

app.get('/', (req, res) => res.sendFile('index.html',{ root : __dirname}))
app.get('*', (req, res) => res.sendFile('index.html',{ root : __dirname}))

Answer №2

In order to successfully redirect all routes to the main file index.html, you need to ensure that your main route is set up properly. Here's how you can achieve this:

// Main route
app.use('/api/example', require('./routes/example')); 
// Auxiliary routes
app.get('/', (req, res) => res.sendFile('index.html', { root : __dirname + '/public'}))
app.get('*', (req, res) => res.sendFile('index.html', { root : __dirname + '/public'}))

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

Step-by-step guide to adding a skew overlay to your video

I am experimenting with creating a skewed overlay on a video playing in the background at full width. Currently, the skew overlay is functioning perfectly. What if I want it to appear in the bottom-right corner instead of the top-left corner? Would I need ...

Obtain data attributes using JQuery's click event handler

I'm facing an issue with a div structure setup as follows: <div class='bar'> <div class='contents'> <div class='element' data-big='join'>JOIN ME</div> <div class=& ...

During bundling, utilize an npm script to copy the package.json file to the dist directory

Currently, I am facing a challenge while trying to enhance my npm bundle script. Although the initial part is functioning smoothly, I am encountering difficulties in including three additional files along with the bundle. At present, my script looks like ...

Additional unnecessary event listeners (deleteComponent) were provided to the component but could not be inherited automatically

Dear community, I am facing an issue with emitting events from my child component to the parent. Strangely, all other components work perfectly fine with the same code except for this particular one. Let me provide you with the relevant code snippets: Ch ...

Effective methods for transferring parameters between two separate JavaScript files within an express.js application

Currently, I am working with Express.js and facing a challenge in passing parameters from one JavaScript file to another. How can this be accomplished? The two files involved are 1. process.js var WebPageTest = require('webpagetest'); var wpt ...

Transferring form data from Jade to Node.js for submission

My Jade template includes the following form structure: form(action='/scheduler/save/' + project.Id, method='post') div.form-group label.control-label.col-md-2 RecurringPattern di ...

Top method for saving information on page for Ajax calls

On my dynamically generated page, there is an array of data produced by php that I want to utilize for an ajax request. However, I am unsure of the best method to store this data on the page as it is not sensitive and does not involve a form. Currently, I ...

Implementing onClick event handling in Material UI components using Typescript

I am attempting to pass a function that returns another function to material UI's onTouchTap event: <IconButton onTouchTap={onObjectClick(object)} style={iconButtonStyle} > <img alt={customer.name} className="object-img" src={obj ...

Online application for saving a vast quantity of information on the user's device

Is there a way for a web application to store an extensive amount of data client-side, allowing for millions of records to be accessed offline by users exclusively on Chrome? I initially considered indexedDb, but I discovered it becomes almost unusable wi ...

Trouble with Excel Office Script setInterval functionality

Trying to automatically recalculate an Excel worksheet every second using Office Script. Unfortunately, my initial approach did not succeed. function sendUpdate(sheet: ExcelScript.Worksheet) { console.log('hi'); sheet.calculate(true); } func ...

Is there a way for me to discover the top trending photos on Instagram today?

Finding information on the Instagram API can be quite challenging due to poor documentation. Is there a method available to discover the most liked Instagram photos by location, such as identifying the top picture liked by Danish users today? Any insight ...

How to Use JavaScript Function to Rotate an Entire Webpage

For my final project in a web design class, we were tasked with creating a website that showcases our skills. I've completed the assignment and now I want to add some interesting features to make it stand out. I'm interested in using -webkit-tra ...

What is the process for dynamically checking in a node in jstree?

I am utilizing Jstree from https://github.com/vakata/jstree. I have successfully loaded the tree structure, and now I want to bind checked checkboxes from an array of data. By default, the nodes have unique ids. I will check the id of each node in the arra ...

Error: The current component does not have a template or render function specified. Check the <App>

I am a beginner in Vue js and I am facing an issue while running my application. It is showing an empty page with the error message: Component is missing template or render function. at <App>. Additionally, there is also a warning from Vue Router sa ...

Difficulty Sorting Dates in Material UI DataGrid

I have a DataGrid in Material UI, and one of my columns displays dates. Following the guidance from the Material UI documentation, I have set the type to "date" in the column array: { field: "submittedAt", headerName: "Submitted", minWidth: 150, flex: 2, t ...

How to clean a string from PHP code using jQuery

Looking for a solution to extract PHP code from a string. The string I have contains PHP code that needs to be removed. text = '<?php // This is a test sample ?> This is a description'; text.replace(/\<\?.*\?\?\ ...

PHP does not receive the uploaded image

I have encountered an issue while trying to create a form for editing a product. Whenever I upload an image, my PHP code is unable to locate the image and throws the following error: Notice: Undefined index: image in C:\xampp\htdocs\pages&bs ...

Retrieve the input field's value with Selenium, verify its accuracy, and proceed to log a message to the console

Hey there! I'm facing a challenge while working with Selenium Webdriver, specifically Chrome Webdriver and writing tests in JavaScript. The problem is in a section of the code where I can't seem to grab the value typed into an input field using t ...

Obtaining a fresh access token from a refresh token using the googleapis npm library

I've been searching everywhere for an explanation, but I can't seem to find one. The documentation I've read says that refresh tokens are used to obtain new access tokens, but it doesn't explain the mechanics behind it. Normally, I wou ...

Looking for a solution to the issue of updating quantity in a shopping cart with Vue and

Whenever I try to increase or decrease the quantity on my shopping cart checkout page by clicking the + or - buttons, it doesn't update in real-time. However, if I navigate back to the product page and then return to the checkout page, I can see that ...