nuxt router.js automatically updates how to prevent this? - javascript

I have a nuxt project. And located in the .nuxt file there is a router.js file when i want to add my own code to it like this:
routes: [{
path: "/ingelogd",
component: _0716b7e1,
name: "ingelogd",
meta: {requiresAuth: true}
}]
router.beforeEach((to, from, next)=> {
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
const isAuthenticated = firebase.auth().currentUser;
if(requiresAuth && !isAuthenticated) {
next("/reserveren")
} else {
next()
}
})
it automatically updates the code to this:
routes: [{
path: "/ingelogd",
component: _0716b7e1,
name: "ingelogd",
}]
Is there someone who knows what the problem is please let me know.

You shouldn't edit any file in your .nuxt directory, here is the docs about it.
You should use router middlewares to execute this kind of logic, take a look!

You should not modify any file in the .nuxt directory. In this situation you should work with middleware,
in middleware folder in the project root add file named auth.js with a content like :
export default function ({ app,route }) {
app.router.beforeEach((to, from, next)=> {
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
const isAuthenticated = firebase.auth().currentUser;
if(requiresAuth && !isAuthenticated) {
next("/reserveren")
} else {
next()
}
})
}
Then, in your nuxt.config.js add :
router: {
middleware: 'auth'
}

Related

MIME Error when using Vue-Router and Express

Everytime I want to access a specific route in Express I get the followwing error in my browser while also having a default and blank Vue HTML without content. Everything works in Vue debug mode but after building everything, only the Home page and the 404 page works.
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
In Express I have the following code:
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
this.app.use(express.static(`${__dirname}/html`));
this.app.get('/*', (req, res) => res.sendFile(`${__dirname}/html/index.html`));
In my router.ts in vue I have the following code:
import { defineAsyncComponent } from "vue";
import { createRouter, createWebHistory } from "vue-router";
import Natives from '../views/Natives.vue';
const router = createRouter({
routes: [
{
path: "/",
name: "Home",
component: defineAsyncComponent(() => import('../views/Home.vue')),
meta: {
name: "Home",
},
},
{
path: "/gta",
name: "GTA V",
component: defineAsyncComponent(() => import("../views/GTA.vue")),
meta: {
name: "GTA"
}
},
{
path: "/gta/natives",
name: "Natives",
component: Natives,
meta: {
name: "GTANatives",
},
},
{
path: '/gta/natives/:hash',
name: 'Native',
component: defineAsyncComponent(() => import("../views/DetailedNative.vue")),
meta: {
name: "DetailedNative"
}
},
{
path: "/:pathMatch(.*)*",
name: "Page not found!",
component: defineAsyncComponent(() => import("../views/NotFound.vue")),
meta: {
name: "NotFound",
},
},
],
history: createWebHistory(),
});
I appreciate any help.
EDIT:
So I found out when this happens. So basically if there are more than two routes for example /gta/native or simply /a/b this error appears even if the page doesn't exist. But I still can't figure out how and why.
It seems mime module does not have a type mapping for vue ext.
You can check from https://github.com/broofa/mime/tree/main/types
https://expressjs.com/en/4x/api.html#express.static
Since express.static middleware support setHeaders option, you can set the header by self.
const express = require('express')
const app = new express();
app.use(express.static(__dirname + '/public', {
setHeaders: (res, path, stat) => {
if (/\.vue/i.test(path))
res.setHeader('Content-Type', 'application/javascript')
}
}))
app.listen(55555, '0.0.0.0', () => {
const http = require('http');
http.get('http://127.0.0.1:55555/test.vue', res => console.log(res.headers['content-type']))
});
Test output
$ node app
application/javascript
So I found the answer somehow. Everything was caused because I had a "corrupted" vite.config.ts. After removing base: './', everything worked flawlessly.

Vue app shows blank when accessing through network on development mode. Seems like it's not rendering

I'm building a website using VueJs and it works perfect with no errors on the localhost, and I can access it locally in the same computer using the IP address as well. I used to be able to open the website within my network to test it using my phone with the IP address using port 8080. For some reason I can't do that anymore, my phone seems to be able to connect correctly because the console shows the firebase development warning but that's about it. It doesn't seem to be rendering the actual website since it shows blank.
last thing I remember installing before this happened was persistedState and I did so using npm like all the other plugins I use. I don't think this is causing the issue but I thought it was worth mentioning.
this is my Vue.config file:
const path = require("path");
module.exports = {
publicPath:
process.env.NODE_ENV === "production" ? "/metronic/vue/demo3/" : "/",
configureWebpack: {
resolve: {
alias: {
// If using the runtime only build
vue$: "vue/dist/vue.runtime.esm.js" // 'vue/dist/vue.runtime.common.js' for webpack 1
// Or if using full build of Vue (runtime + compiler)
// vue$: 'vue/dist/vue.esm.js' // 'vue/dist/vue.common.js' for webpack 1
}
}
},
chainWebpack: config => {
config.module
.rule("eslint")
.use("eslint-loader")
.tap(options => {
options.configFile = path.resolve(__dirname, ".eslintrc.js");
return options;
});
},
css: {
loaderOptions: {
postcss: {
config: {
path: __dirname
}
},
scss: {
prependData: `#import "#/assets/sass/vendors/vue/vuetify/variables.scss";`
}
}
},
transpileDependencies: ["vuetify"]
};
this is my main.js (i skipped all the imports):
router.beforeEach(async (to, from, next) => {
console.log("router");
const user = await authf.currentUser;
(user) ? await store.dispatch("fetchUserProfile", user) : "";
const requiresAuth = await to.matched.some(record => record.meta.requiresAuth);
const isAuthenticated = await store.state.userProfile;
if (isAuthenticated.email != null) {
(requiresAuth) ? next() : next("/Dashboard");
} else {
(requiresAuth) ? next("/Login") : next();
}
// reset config to initial state
store.dispatch(RESET_LAYOUT_CONFIG);
// Scroll page to top on every route change
setTimeout(() => {
window.scrollTo(0, 0);
}, 100);
});
let app;
authf.onAuthStateChanged(async(user) => {
if (user) {
await store.dispatch('fetchUserProfile', user)
}
});
new Vue({
router,
store,
i18n,
vuetify,
firebase,
axios,
render: h => h(App)
}).$mount("#application");
when I do npm run serve it gives me the local access through localhost:8080 and the network access through 192.168.1.137:8080 as it always has. I have access with no console errors in my computer, but the app wont render when accessing through network.

How can I localize routes with the nextJs and next-i18next like an URL alias?

I'm using NextJs 10.0.5 with next-i18next 8.1.0 to localize my application. As we all know nextJs 10 has subpath routing for internationalized routing. In addition, I need to change the page names by language. For example, I have a contact-us file inside the pages folder. When I change the language to Turkish, I have to use localhost:3000/tr/contact-us. However, I want to use localhost:3000/bize-ulasin to access the contact-us page when the language is Turkish. So there are two URLs and only one page file.
It works when I use custom routing with express js in the server.js file. However, when I want to access the "locale" variable within the getStaticProps function in the contact-us file, I cannot access it. The getStaticProps function returns undefined for "locale" variable when I use localhost:3000/bize-ulasin URL.
server.js
const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");
const app = next({ dev: process.env.NODE_ENV !== "production" });
const handle = app.getRequestHandler(app);
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl;
if (pathname === "/bize-ulasin") {
app.render(req, res, "/contact-us", query);
}else{
handle(req, res, parsedUrl);
}
}).listen(3000, (err) => {
if (err) throw err;
console.log("> Ready on http://localhost:3000");
});
});
/pages/contact-us-file
import { Fragment } from "react";
import Head from "next/head";
import { useTranslation } from "next-i18next";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
const ContactUs = () => {
const { t } = useTranslation("common");
return (
<Fragment>
<Head>
<title>Contact-Us</title>
</Head>
</Fragment>
);
};
export const getStaticProps = async ({ locale }) => {
console.log(locale); // When I use the URL localhost: 3000/bize-ulasin, it returns undefined.
return {
props: {
...(await serverSideTranslations(locale, ["common"])),
},
};
};
export default ContactUs;
How can I access the "locale" variable with getStaticProps? Or, how can I use the following URLs with the same page file?
->localhost:3000/contact-us
->localhost:3000/bize-ulasin
I also faced the same problem today. That's how I solved the issue.
First of all, delete the server.js file. With Next.JS 10, using server.js will create conflict with the i18n routes and you won't be able to get the locale data in getStaticProps.
NextJS has a beautiful method named rewrites. We will use that instead of our server.js file. For example, if you have a page named contact-us-file, we can rewrite our next.config.js file as
const { i18n } = require('./next-i18next.config')
module.exports = {
i18n,
async rewrites() {
return [
{
source: '/contact-us',
destination: '/en/contact-us-file',
},
{
source: '/bize-ulasin',
destination: '/tr/contact-us-file',
},
]
},
}
As you are already using Next-i18next, I hope you are familiar with the file that I am importing.
Now If you try to navigate localhost:3000/contact-us and localhost:3000/bize-ulasin you should be able to access your contact us page.

Vue Router Navigation Guard Dynamic Import

I want to dynamically import data from component file to router file and allow next() depending upon value of imported data.
in App.vue I'm triggering this.$router.push({name: "Dashboard"}) when data authenticated: false changes to true. I'm triggering it with watch.
Problem is, router file will always receive original value false even with dynamic importing.
App.vue
watch: {
authenticated(){
console.log(this.authenticated) //Outputs 'true'
this.$router.push({name: 'Dashboard'}); //Triggers routing
}
}
router file (index.js)
{
path: '/dashboard',
name: 'Dashboard',
component: Dashboard,
beforeEnter(to, from, next){
(async ()=>{
const mod = await import('../view/App.vue'); //Dynamic import
let result = mod.default.data().auth; //Access 'authenticated' value from App.vue
console.log(result); //Output is 'false', but it should be 'true'
result ? next() : next({name: 'Login'});
})()
}
}
I tried many different async methods as well but nothing worked.
Use In-Component Guard in your App.vue as specified here and remove the authentication login from router file:
beforeRouteLeave(to, from, next) {
if (to.name === 'Dashboard' && this.authenticated) {
next();
}
else {
next({ name: 'Login' });
}
}

Vue Router: URL does not load correct component while router-link does

My project uses Vue2 and Vue Router. I want to be able to load the component Stats by typing in the URL http://example.com/stats.
URL http://example.com/stats does not work, I'm redirected to / and it loads the App component
<router-link :to="/stats">Go to stats</router-link> works perfectly
I would like to know whether it is a Vue Router issue or a server configuration issue. I'd like to mention the fact that I experience this issue both in my localhost and my server using nGinx.
How could I fix this?
app.js:
const routes = [
{ path: '/', component: App },
{ path: '/stats', component: Stats },
{ path: "*", component: PageNotFound },
{ path: '/admin', meta: { requiresAdmin: true }, component: Admin},
{ path: "/not-authorized", component: NotAuthorized },
];
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'history',
routes,
})
const app = new Vue({
el: '#app',
router,
data () {
return {}
},
});
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAdmin)) {
if (!Store.state.isAdmin) {
axios.post('/isAdmin').then((response) => {
if(response.data.isAdmin){
next();
}
else {
next({
path: '/not-authorized',
})
}
});
}
else {
next();
}
}
else {
next();
}
}
else {
next(); // make sure to always call next()!
}
});
Have you configured your web-server to return the same page regardless of the URL?
That way your app can load, and the URL is preserved so routing can take over and select the right component once it's loaded.
This answer https://stackoverflow.com/a/7027686/7816087 suggests the following config for nginx:
location / {
try_files $uri /base.html;
}
Go to your Laravel routes and put this:
Route::any('{all}', function () {
return view('index'); // if your main view is "index"
})
This will ensure that deep linking is working properly on all request handled by Laravel.
Here is what I did
Route::get('/stats', 'HomeController#home');

Categories