I am using Vue router with history mode. On button click on the current page I route it to next page. On second page when i reload i get a 404. Is there a way to handle this in Vue and redirect it to home page.
export default new Router({
mode: "history",
routes: [
{
path: "/",
name: "first",
component: First
},
{
path: "/abc",
name: "abc",
component: Second,
props: true
},
you can use hash mode inested of history mode to resolve the problem on your router
let router = new Router({
mode: "hash",
routes: [
{
//and the urls with path on here ...
if any one of is facing the issue even after trying above solution, please find below method.
If you have vue.config.js which has
module.exports = {
publicPath: process.env.PUBLIC_URL || "", // <-- this is wrong
...
};
either remove the vue.config.js or try removing the publicPath from the exports object.
Also you can try below method if you dont want to remove the publicPath
module.exports = {
publicPath: process.env.PUBLIC_URL || "/", // <-- this is correct now (and default)
transpileDependencies: ["vuetify"],
};
This is related to how the history mode in Vue Router works. I have created a writeup about it, with a solution as well.
Depends on your server implementation you need to enable URL Rewrites there. Here's how this would be implemented using Express/Node.js:
const express = require('express');
const app = express();
const port = 80;
const buildLocation = 'dist';
app.use(express.static(`${buildLocation}`));
app.use((req, res, next) => {
if (!req.originalUrl.includes(buildLocation)) {
res.sendFile(`${__dirname}/${buildLocation}/index.html`);
} else {
next();
}
});
app.listen(port, () => console.info(`Server running on port ${port}`));
For more info, check out https://blog.fullstacktraining.com/404-after-refreshing-the-browser-for-angular-vue-js-app/. HTH
This usually happens, when you deploy the page to a hosting server. Check the official docs for more background info and specifiy tipps for different hosting entvironments
https://router.vuejs.org/guide/essentials/history-mode.html
We have resolved this on backend, we have filter where we intercept the request and redirect it to home page. We have made it configurable.
Related
I need a vanilla js router for a spa site. Here on the github I found it seems like an ideal implementation, but there is one problem. This implementation, and everything that I found on the Internet, works well only with hash, through the history api that I need, they refuse to work, tell me what I'm doing wrong, or tell me another working implementation.
So I just take the Router class code, and set the routes I need:
const router = new Router({
mode: 'history',
root: '/'
});
router
.add('', () => {
console.log('deafult page');
}).add('settings', () => {
console.log('settings page');
}).add(/task-list/, () => {
console.log('task-list page');
})
And only the console.log('deafult page') is executed, if I enter http://localhost:3000/settings in the line, then it will give me Cannot GET /settings
if i use click event
document.addEventListener('click',()=>router.navigate('settings'))
then the link will become http://localhost:3000/settings, but the code console.log('settings page'); will not work
Just need to add webpack settings
devServer: {
contentBase: './dist',
port: 3000,
historyApiFallback: true, // its enable SPA routing through historyApi
}
My goal is creating pages from local plugin. I wrote a custom plugin named my-custom-plugin. I've also installed gatsby-plugin-page-creator plugin to automatically create pages from my components outside default pages directory.
This is my project structure:
plugins
/my-custom-plugin
/gatsby-node.js
/package.json
src
/components
/pages
/single.js
gatsby-config.js
gatsby-node.js
...etc
gatsby-config.js (from root):
module.exports = {
plugins: [
`my-custom-plugin`,
{
resolve: `gatsby-plugin-page-creator`,
options: {
path: `${__dirname}/src/components/pages`,
}
},
]
}
plugins/my-custom-plugin/gatsby-node.js
const path = require('path')
const location = path.resolve(__dirname, '..', '..', '/src/components/pages')
exports.createPages = ({ actions }) => {
const { createPage } = actions
createPage({
path: `/sample-page`,
component: `${location}/single.js`,
context: {
slug: 'sample-page'
}
})
}
Unfortunately, I got error message The plugin "my-custom-plugin" created a page with a component that doesn't exist when running gatsby develop. Am I doing wrong? Any help?
Regards.
https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-plugin-page-creator
You don't need a custom plugin. The README states that you only need to insert the config into gatsby-config.js.
Your current local plugin tries to do exactly that what the page-creator plugin already does.
my react router is working fine with dev env, this is what I did in webpack dev server:
historyApiFallback: {
index: 'index.html',
}
so in production mode I wanted to do the same, I did it in express like this:
const indexPath = path.join(__dirname, '../public/index.html')
const publicPath = express.static(path.join(__dirname, '../public'))
app.use('/public', publicPath)
app.use('/graphql', graphQLHTTP(async (req) => {
let { user } = await getUser(req.headers.authorization);
if(!user) {
user = 'guest'
}
return {
schema,
pretty: true,
graphiql: true,
context: {
user,
}
}
}));
app.get('/', function (_, res) { res.sendFile(indexPath) });
I did not change anything with react-router-dom so I am am assuming the error is in my express config. so what's the equivalent of historyApiFallback in production mode? below is my webpack bundle config:
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js',
publicPath: '/public/'
},
in my html I reference the bundle like this:
<script type="text/javascript" src="/public/bundle.js"></script>
I think a have the right config but when I reload I get cannot GET Error 404?
You should add this line to your app:
app.get('*', function (_, res) { res.sendFile(indexPath) });
Or you should use this package better: https://github.com/bripkens/connect-history-api-fallback
You should read more about history mode:
To get rid of the hash, we can use the router's history mode, which leverages the history.pushState API to achieve URL navigation without a page reload:
When using history mode, the URL will look "normal," e.g. http://oursite.com/user/id. Beautiful!
Here comes a problem, though: Since our app is a single page client-side app, without a proper server configuration, the users will get a 404 error if they access http://oursite.com/user/id directly in their browser. Now that's ugly.
Not to worry: To fix the issue, all you need to do is add a simple catch-all fallback route to your server. If the URL doesn't match any static assets, it should serve the same index.html page that your app lives in. Beautiful, again!
My problem is that every time I load my link. Ex:
"https://www.example.com/" it will redirect to
"https://www.example.com/design-brief" since I configured it in my routing.ts.
But when I will use the link "https://www.example.com/design-brief" and enter in my address bar, it will show an error in console log.
"GET https://www.example.com/design-brief 404 ()"
const APP_ROUTES: Routes = [
{ path: 'design-brief', component: DesignBriefComponent },
{ path: 'design-evaluation', component: DesignEvaluationComponent },
{ path: '', redirectTo: '/design-brief', pathMatch: 'full' },
{ path: "**",redirectTo:"/design-brief" } ];
Here is my code in my routing.ts
See my answer here for a more detailed explanation of why this is happening.
In a nutshell, you have 2 options:
Configure your web server to always respond with the
index.html whenever it detects a 404 - that way, Angular will always
load and its routing service will handle the navigation on the
client side.
Change your app's locationStrategy to the Hash location strategy as
described here. However, that would change your app's URLs, and it's
not that desirable in my opinion.
You don't need the empty path and the ** path, only the ** path with pathMatch 'full':
const APP_ROUTES: Routes = [
{ path: 'design-brief', component: DesignBriefComponent },
{ path: 'design-evaluation', component: DesignEvaluationComponent },
{ path: "**",redirectTo:"design-brief",pathMatch: 'full' } ];
and redirect does not need the slash (/) in front of design-brief
I Solved it by using Hash location strategy.Add following code to the imports portion of the #ngModule and prefix all your hyperlink with #
and also refer offecial link for info
RouterModule.forRoot(
appRoutes,{ useHash: true }
)
I have some routes defined in my App component:
#routeConfig([
{
path:'login',
name: 'Login',
component: Login
}}
And a very basic node express loader:
var express = require('express');
var app = express();
app.use(express.static('app'));
app.use('/node_modules', express.static(__dirname + '/node_modules/'));
app.get('/home', function(req, res, next) {
next();
});
app.listen(3000, function () {
console.log('Serverlistening on port 3000!');
});
My issue is that going to '/login'/ is intercepted by node express and it says 'cannot get /login'. I want Angular2 to handle it. It worked fine in node lite server but not in express.
How can I configure express to ignore these routes and allow Angular to handle them?
You could try to configure your route this way:
#routeConfig([
{
path:'/login', // <----------
name: 'Login',
component: Login
}
])
Edit
If you hit the request directly, you need to have something to return the content of the index.html file for the request into your Express application.
This must be done for each route defined in Angular2. Otherwise you will have 404 errors.
See this question for more details:
Angular 2 : 404 error occur when i refresh through Browser