Laravel API route doesnt work on vue3 vue-router - vuejs3

Hey everyone laravel 9 vue 3 and vue-router the problem is that localhost:8000/api/admin/login is not available. Transition opens non-existent vue components page Can you suggest how to exclude api prefix from vue router.
Backend: Laravel 9
PHP: 8.0
Fronted: Vue3,axios, vue-routera
web.php
Route::get('{any?}', function () {
return view('welcome');
})->where('any', '.*');
api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\Admin\UserController;
Route::any('login', [UserController::class, 'login']);
Route::any('register', [UserController::class, 'register']);
Route::group(['middleware' => 'auth:api'], function () {
Route::get('logout', [UserController::class, 'logout']);
Route::get('user', [UserController::class, 'user']);
});
app.js
import {createApp} from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import axios from 'axios'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(ElementPlus)
app.use(router, axios)
app.config.globalProperties.$axios = axios
app.mount("#app")
router.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from './components/Main/HomeComponent.vue';
import Login from './components/Main/LoginComponent.vue';
import Dashboard from './components/Main/DashboardComponent.vue';
const routes = [
{
path: '/',
name: 'home',
component: Home,
meta: {
requiresAuth: false,
title: 'Home',
}
},
{
path: '/login',
name: 'login',
component: Login,
meta: {
requiresAuth: false,
title: 'Login',
}
},
{
path: '/dashboard',
name: 'dashboard',
component: Dashboard,
meta: {
requiresAuth: true,
title: 'Dashboard',
}
}
]
const router = createRouter({
history: createWebHistory(),
mode: 'history',
routes,
linkExactActiveClass: 'active'
});
// eslint-disable-next-line no-unused-vars
router.beforeEach((to, from) => {
document.title = to.meta.title;
if (to.meta.requiresAuth === true && !this.$store.authenticated) {
return this.$router.push('/login');
}
})
export default router
In the end, calling api route.php worked correctly

Related

Vue3 + Firebase Authentication (onAuthStateChanged) Problem

I'm working on vue3 and firebase. I'm having a problem with the onAuthStateChanged.
If I make all the router without the children it works but, if I add /admin and then put the children routes there I cannot stay logged in anymore.
This is my main.js file:
// main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import { auth } from './plugins/firebase'
import { onAuthStateChanged } from 'firebase/auth'
import App from './App.vue'
import router from './router'
import './assets/styles/index.css'
import { useAuthenticationStore } from './stores/authentication'
let newApp
onAuthStateChanged(auth, (user) => {
if (!newApp) {
newApp = createApp(App)
newApp.use(createPinia())
newApp.use(router)
const authStore = useAuthenticationStore()
authStore.user = user
newApp.mount('#app')
}
})
This is my router. You can see that I need to validate if the user is logged in inside /admin
//router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import { useAuthenticationStore } from '../stores/authentication'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: () => import('../views/PublicView.vue'),
children: []
},
{
path: '/admin',
name: 'admin',
children: [
{
path: '',
name: 'dashboard',
component: () => import('../views/admin/HomeView.vue'),
meta: {
requiresAuth: true,
layout: 'PrivateLayout'
}
},
{
path: 'login',
name: 'login',
component: () =>
import('../views/admin/authentication/LoginView.vue'),
meta: {
requiresAuth: false,
layout: 'AuthenticationLayout'
}
},
{
path: 'password',
children: [
{
path: 'recovery',
name: 'password-recovery',
component: () =>
import(
'../views/admin/authentication/PasswordRecoveryView.vue'
),
meta: {
requiresAuth: false,
layout: 'AuthenticationLayout'
}
},
{
path: 'reset',
name: 'password-reset',
component: () =>
import('../views/admin/authentication/PasswordResetView.vue'),
meta: {
requiresAuth: false,
layout: 'AuthenticationLayout'
}
}
]
}
]
},
{
path: '/404',
component: () => import('../views/NotFound.vue')
},
{ path: '/:catchAll(.*)', redirect: '/404' }
]
})
router.beforeEach((to, from, next) => {
const authenticationStore = useAuthenticationStore()
const requiresAuth = to.matched.some((record) => record.meta.requiresAuth)
const isAuthenticated = authenticationStore.user !== null
if (to.path === '/admin/login' && isAuthenticated) {
next('/admin/dashboard')
}
if (requiresAuth && !isAuthenticated) {
next('/admin/login')
}
next()
})
export default router
//plugins/firebase.js
import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
// Firebase configuration
const firebaseConfig = {
apiKey: import.meta.env.VITE_API_KEY,
authDomain: import.meta.env.VITE_AUTH_DOMAIN,
projectId: import.meta.env.VITE_PROJECT_ID,
storageBucket: import.meta.env.VITE_STORAGE_BUCKET,
messagingSenderId: import.meta.env.VITE_MESSAGING_SENDER_ID,
appId: import.meta.env.VITE_APP_ID,
measurementId: import.meta.env.VITE_MEASUREMENT_ID
}
// Initalize Firebase
const firebaseApp = initializeApp(firebaseConfig)
const auth = getAuth(firebaseApp)
export { auth }

Not able to fetch url params in vue js

Hi I am trying to fetch the value for "customerID" and "iot" in MyIOT.vue. When I enter the url http://localhost:8080/5/345435 it gives me an empty value for params. I tried both ways using routing and props. None of them is working. Not sure where I am getting it wro
main.js
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import MyIot from './components/MyIOT.vue'
//import router from './router/index.js'
const routes = [
// {
// path: '/',
// redirect: '/:customerID/:iot'
// },
{
path: '/:customerID/:iot',
component: MyIot,
//props: true,
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
const app = createApp(App).use(router);
app.mount('#app');
App.vue
<template>
<MyIot />
</template>
<script>
import MyIot from './components/MyIOT.vue'
//import axios from "axios";
export default {
name: "App",
components: {
MyIot,
},
};
</script>
components/MyIOT.vue
<template>
<div>customer id is: {{customerID}} and iot is : {{iot}}
</div>
</template>
<script>
import { useRoute } from 'vue-router'
export default {
name: 'MyIot',
//props: ['customerID', 'iot'],
setup() {
const route = useRoute();
console.log(route.params);
}
}
</script>

Vue3 - Routes if page doesn't exist with dynamic routes not working with my 404?

I am using Vue3 and have my Router setup for detail pages. Any title returns the same data and 404 is being ignored even after adding the regEx inside the routes.
Routes:
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import HomeView from "../views/HomeView.vue";
import ErrorView from "../views/ErrorView.vue";
const routes: Array<RouteRecordRaw> = [
{
path: "/",
name: "home",
component: HomeView,
},
{
path: "/about",
name: "about",
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () =>
import(/* webpackChunkName: "about" */ "../views/AboutView.vue"),
},
{
path: "/article/:slug",
name: "article",
component: () =>
import(/* webpackChunkName: "article" */ "../views/ArticleView.vue"),
},
{
path: "/404",
name: "PageNotExist",
component: () => import("../views/ErrorView.vue"),
},
{
path: "/:catchAll(.*)", // Unrecognized path automatically matches 404
redirect: "/404",
},
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
export default router;
Article:
<template>
<div>
<h1>{{ data.title }}</h1>
<h3>{{ data.textarea }}</h3>
</div>
</template>
<script lang="ts">
import { useSanityFetcher } from "vue-sanity";
import { defineComponent } from "vue";
export default defineComponent({
name: "ArticleView",
setup: () => {
const articleQuery = `*[_type == "article"][0] {
title,
textarea,
}`;
const options = {
listen: true,
clientOnly: true,
};
const { data } = useSanityFetcher<object>(articleQuery, options);
return { data };
},
});
</script>

NextJS locale change with dynamic routes

Locale change works well in my next.js app, except for with dynamic routes. In the browser address bar I do get the transition from http://localhost:3000/client/home/profile to http://localhost:3000/de/client/home/profile, but the page gives a 404 error...
My dynamic page [tab].tsx
import router from 'next/router'
import dynamic from 'next/dynamic'
import styled from 'styled-components'
import {useTranslation, i18n} from 'next-i18next'
import {useEffect, useState, useContext} from 'react'
import {serverSideTranslations} from 'next-i18next/serverSideTranslations'
import Layout from 'layouts'
import {DB, PATH} from 'utils/constants'
import {GlobalContext} from 'utils/contexts'
import {Tabs, LanguageSelector} from 'components/ui'
import {ChartData, ChartDataPoint, UsageStats} from 'utils/types'
import {getData, toTitleCase, isClient, emailVerified} from 'utils/helpers'
const Docs = dynamic(() => import('components/client/docs'))
const Stats = dynamic(() => import('components/client/stats'))
const Profile = dynamic(() => import('components/client/profile'))
const Tab = ({tab}) => {
const {t} = useTranslation()
return (
<Layout>
<LanguageSelector />
<Tabs
basePath={'/client/home'}
tab={tab}
tabs={[
{
slug: 'stats',
label: t('client.home.stats'),
component: <Stats data={data} />
},
{
slug: 'profile',
label: t('client.home.profile'),
component: <Profile client={client} />
},
{
slug: 'docs',
label: t('client.home.docs'),
component: <Docs />
}
]}
/>
</Layout>
)
}
export const getStaticProps = async ({params, locale}) => ({
props: {
tab: params.tab,
...await serverSideTranslations(locale)
}
})
export const getStaticPaths = async () => {
return {
paths: [
{params: {tab: 'stats'}},
{params: {tab: 'profile'}},
{params: {tab: 'docs'}}
],
fallback: false
}
}
export default Tab
I do the locale switching in my LanguageSelector.tsx:
import router from 'next/router'
import {i18n} from 'next-i18next'
import {useState, useEffect} from 'react'
import {Select} from '.'
import {LANGUAGES} from 'utils/constants'
export const LanguageSelector = () => {
const [locale, setLocale] = useState(i18n.language)
useEffect(() => {
const {pathname, asPath, query} = router
router.push({pathname, query}, asPath, {locale})
}, [locale])
return (
<Select
borderless
isSearchable={false}
value={i18n.language}
options={LANGUAGES.filter(language => language !== i18n.language)}
onValueChange={setLocale}
/>
)
}
Any ideas where my mistake is?
If you are using getStaticPaths with in-build Next.js i18n routing then you also need to return locale key with your paths, like that:
export const getStaticPaths = ({ locales }) => {
return {
paths: [
{ params: { slug: 'post-1' }, locale: 'en-US' },
{ params: { slug: 'post-1' }, locale: 'fr' },
],
fallback: true,
}
}
More info in the docs

I receive error after reboot page in Vue3

Delab some code changes Vue3-Vite.
I receive error after reboot page in Vue3.
Uncaught ReferenceError: Cannot access 'router' before initialization
router\index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
]
App.vue
<router-link
to="/"
>
<button
type="button"
class="btn btn-outline-primary mx-4"
>
Home
</button>
</router-link>
router\index.js
import { createWebHistory, createRouter } from "vue-router";
const history = createWebHistory();
const routes = [/* Routes*/];
const router = createRouter({ history, routes });
export default router;
add router in main.js
import router from "./router";
createApp(App).use(router).mount("#app");
At no time does it see how you use a router in your app when it is mounted.
In all cases you should do something like
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import { createApp} from 'vue';
const routes = createRouter([
{
path: '/',
name: 'Home',
component: Home
},
)]
const app = createApp(Home);
app.use(routes);

Resources