Angular Router Get 404 Bug? - javascript

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 }
)

Related

Missing Script generated by Webpack(development) on first page load

the first time i load the login page the login.js script doesn't load , only the shared.js bundle loads (which has bootstrap js/css and toastr css), if i refresh the page everything loads without problems and after that there are no problems.
Pretty much every time i restart my local server i need refresh the login page to be able to login
my webpack config is as follows
export default {
entry: {
shared: [
'./src/3rdparty/bootstrap/bootstrap.min.js',
'./src/3rdparty/bootstrap/bootstrap.min.css',
'./src/3rdparty/toastr/toastr.min.css',
],
login : {
import: './src/pages/login.js',
filename: 'main/login.js',
dependOn: 'shared',
chunkLoading: false,
}
},
output:{
path: fileURLToPath(new URL('public',import.meta.url)),
clean:true,
},
resolve:{
extensions: ['.js']
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
],
mode: 'development'
}
The project has been build using Node 16.17 / Expressjs 4
It works without problems if i change the mode to production
Going to write in case i encounter the same issue again:
after adding the compression library i cannot replicate the issue
another issue that i had was that when i was returning messages from the server with the status 400, it would return a invalid string Ex:
{ok:true, description:"username invalid"
always missing the closing bracket }
this issue has also been resolved by using compression middleware

Vue 3 & Vite built application shows blank page

I have a problem trying to make a build of a new Vue3.js + Vite.js application. Once my application is finished i made the npm run build action in order to generate the final deployment files.
Problem is that when I try to see the generated page, it only shows a white page.
Opening the inspection tool I can see how the main generated javascript files are like not being found by the static index.html:
Failed to load resource: net::ERR_FAILED index.7b66f7af.js:1
Ok. I found the solution searching a bit, and I see how this problem also occurred actually in Vue 2.
The only thing that you have to do for solvif is add base: './' in your vite.config.js, like this:
import {
defineConfig
} from 'vite'
import vue from '#vitejs/plugin-vue'
import vuetify from '#vuetify/vite-plugin'
const path = require('path')
export default defineConfig({
plugins: [
vue(),
vuetify({
autoImport: true,
}),
],
define: {
'process.env': {}
},
resolve: {
alias: {
'#': path.resolve(__dirname, 'src'),
},
},
base: './',
})
Hope it helps you all!
I had this problem also, and found a solution:
It looks like the awnser given by #javi But it's different. I found out that the situation changes when you deploy your application.
In vite config there is a setting called 'base' filled in like: base: mode === 'production' ? '/nameExample/' : '/', this will put the output of your project on the endpoint : 'nameExample'. If you go in production this fails and shows a blank page, and you need to changes this nameExample to '/' to show the projectbuild online. But than it shows a blank page in development because it mismatches the name of the project. Hope this will help you.

Preloading, lazy loaded pages Ionic 4

In Ionic 3 we had the option to preload pages by doing:
IonicModule.forRoot({
preloadModules: true
});
But when I try to do that in Ionic 4, it gives me an error:
Argument of type '{ preloadModules: boolean; }' is not assignable to parameter of type 'IonicConfig'.
Someones know how to do this in Ionic 4.
Ionic 4 under the hood uses Angular CLI, which supports Lazy Loading Modules. While creating Routes using forRoot(), forChild(). We can define the lazy loaded modules using loadChildren configuration.
const app_routes: Routes = [
{
path: 'home',
loadChildren: 'app/home/home.module#HomeModule'
},
{ path: '', pathMatch: 'full', redirectTo: '/login' },
{ path: '**', pathMatch: 'full', redirectTo: '/login' }
];
RouterModule.forRoot(app_routes);
We are telling ionic/Angular CLI, when user access '/user' location path, we need to load the Home Module as lazyloaded, which will internally load the required components and services.
Ionic Docs: https://beta.ionicframework.com/docs/

Vue router on page refresh gets 404

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.

How to use javascript webworker in webpack?

i'm trying to use web workers in my web app but i'm having a hard time. Adding a new entry to the webpack.config.js does not work.
so, I'm trying to use the npm package called worker-loader but there is no proper example on how to use it. All of my attempts to use it has failed. Can you guys please show me a simple example on how to use it.
import Worker from "worker-loader!./Worker.js";
const myworker = new Worker();
myworker.postMessage(songs);
myworker.onmessage = function(Data) {
//do something
}
my webpack.config.js file is like this with
entry: __dirname + "/js/index.js",
output: {
path: __dirname + "/dist",
filename: "bundle.js"
},
{
module: {
rules: [
{
test: /\.worker\.js$/,
use: { loader: 'worker-loader' }
}
]
}
}
My server tells me the following:
"GET /279b1e1fcb403131377a.worker.js HTTP/1.1" 404
Since my 279b1e1fcb403131377a.worker.js is inside /dist its giving me 404 error. How can i make the request to go inside /dist.
There are plenty of examples given on the official Github page:
https://github.com/webpack-contrib/worker-loader
That should easily get you going.

Categories