Vue JS Production mode refresh causing 404 error

  1. Check the Build Configuration:
  2. Ensure that the Vue project is built for production using the command: npm run build.
  3. Verify the "build" folder contains the necessary files, especially the "index.html" file.

  4. Set Public Path in Vue Config:

  5. If your app is not hosted at the root of the domain, set the publicPath in vue.config.js: js module.exports = { publicPath: process.env.NODE_ENV === 'production' ? '/your-subpath/' : '/', };

  6. Configure Server for History Mode:

  7. If using Vue Router with history mode, configure the server to redirect 404 errors to the index.html file. For example, in a Node.js/Express server: ```js const express = require('express'); const history = require('connect-history-api-fallback');

    const app = express(); app.use(history()); app.use(express.static('dist')); // Replace 'dist' with your build folder

    const port = process.env.PORT || 3000; app.listen(port); ```

  8. Check .htaccess Configuration (if using Apache):

  9. If your app is hosted on an Apache server, ensure the .htaccess file is configured for Vue Router's history mode. Example: apache <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /your-subpath/ RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /your-subpath/index.html [L] </IfModule>

  10. Configure Nginx (if using Nginx):

  11. If using Nginx, ensure the server configuration includes the appropriate location block for Vue Router's history mode: nginx location /your-subpath/ { try_files $uri $uri/ /your-subpath/index.html; }

  12. Verify Base URL in index.html:

  13. Open the index.html file in the "build" folder and ensure the <base> tag is correctly set: html <head> <base href="/your-subpath/"> <!-- other head elements --> </head>

  14. Update Router Mode (if necessary):

  15. In your router configuration (usually in src/router/index.js), ensure that the mode is set to 'history': js const router = new VueRouter({ mode: 'history', // other router configurations });

  16. Check Server Permissions:

  17. Ensure that the server hosting the Vue app has the necessary permissions to access and serve the files in the build folder.

  18. Update Base URL in Axios (if using Axios for API calls):

  19. If your Vue app uses Axios for API calls, ensure that the base URL is correctly set: js axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? '/your-subpath/' : '/';

  20. Test in Different Environments:

    • Test the production build in various environments to identify any environment-specific issues that may be causing the 404 errors.