socketsvue.jsaxiosquasar

Quasar App Routing Problems


I am developing a Quasar App right now. So far I only have a login page and the default layout that quasar provides. I have a separate server I have set up running at port 100. I already set up the proxy to redirect all calls from axios and socket.io to my server which hosts my mySQL database for my application. I already set up my routes and if I manually type in the route in the browser's search I can go to it but once I use this.$router.push() in my login to go to the main page it doesn't navigate to it. For example I'm hosting this app on port 8080. By default it'll go to the login page which is: "localhost:8080". When the login authenticates, the user is supposed to be redirected to the main page within my quasar app using this.$router.push('/main'). However, it does not do this. When I press login, the url just changes to "localhost:8080/?". However, if I manually type in: "localhost:8080/main" in the browser it directs me toward the main page. Here is the code for my routes:

export default [
{ 
    path: '/', 
    component: () => import('components/login'),
  },

  {
    path: '/main',
    component: () => import('layouts/default'),
    children: [
      { path: '', component: () => import('pages/index') },
      { path: 'chat', component: () => import('components/chat')}
    ]
  },

  { // Always leave this as last one
    path: '*',
    component: () => import('pages/404')
  }
]

Here is my code for my login component:

<template>
    <div>
        <form id="login" label="Login">
            <q-input type="text" float-label="Username" v-model="username" /> <br>
            <q-input v-model="password" type="password" float-label="Password" />
            <q-btn input type="submit" @click="authenticate()">Submit</q-btn>
        </form>
    </div>
</template>

<style>
    input{
        margin: 10px;
    }
    #login{
        vertical-align: middle;
        text-align: center;
    }
</style>

<script>

module.exports = {
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    authenticate () {
      this.$axios.post('/api/login', {
        Username: this.username,
        Password: this.password
      })
        .then(response => {
          this.$Socket.emit('LoginInfo', {
            firstname: response.data[0].ClientFirstName,
            lastname: response.data[0].ClientLastName,
            name: response.data[0].ClientFirstName + ' ' + response.data[0].ClientLastName,
            userid: response.data[0].ClientID
          })
          console.log(this.$router)
          this.$router.push({path: '/main'})
        })
        .catch(function (error) {
          console.log(error)
        })
    }
  }
}
</script>

I've spent hours trying to search up what might be the problem but so far I've come up with nothing useful. Maybe it might be a bug? My colleague looked over my code and he sees no problem as well. Hopefully you guys can help me out. I would really appreciate it.

As requested, the server code:

const Express=require('express');
const path=require('path');
var cors = require('cors')
var app = Express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "ChatDB"
});

con.connect(function(err) {
  if (err)throw err;
  /*let query="INSERT INTO Client(ClientUserName, ClientPassword, ClientFirstName, ClientLastName) VALUES(\"jeffrey\", \"penner\", \"Jeffrey\", \"Penner\")";
  con.query(query, function(err, result){
    if(err) throw err;
  })*/
  console.log("Connected!");
});

io.set('origins', 'http://localhost:8080');

app.use(Express.json())
//app.use('/public', Express.static(path.join(__dirname, 'public')));
app.use(cors());

app.post('/login', cors(), function(req, res){
  let a=req.body.Username;
  let b=req.body.Password;
  let query="SELECT ClientID, ClientFirstName, ClientLastName FROM Client WHERE ClientUsername=\'" + a + "\' AND ClientPassword=\'" + b + "\';";
  con.query(query, function (err, rows) {
    if (err){
      throw err;
    }
    else if(rows.length)
    {
      console.log(rows);
      res.json(rows);
    }
  })
});

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
  socket.on('LoginInfo', function(data) {
    console.log(data)
  });
})

http.listen(100, function(){
  console.log('listening on *:100')
});

index.js for router code:

import Vue from 'vue'
import VueRouter from 'vue-router'

import routes from './routes'

Vue.use(VueRouter)

const Router = new VueRouter({
  /*
   * NOTE! Change Vue Router mode from quasar.conf.js -> build -> vueRouterMode
   *
   * If you decide to go with "history" mode, please also set "build.publicPath"
   * to something other than an empty string.
   * Example: '/' instead of ''
   */

  // Leave as is and change from quasar.conf.js instead!
  mode: process.env.VUE_ROUTER_MODE,
  base: process.env.VUE_ROUTER_BASE,
  scrollBehavior: () => ({ y: 0 }),
  routes
})

export default Router

Solution

  • I think you are not importing the routes in main.js as it should and thus the router object it is not accessible in all components.

    I will show you how i have done my routes (simplified examples).

    Routes

    import Vue from 'vue'
    import Router from 'vue-router'
    import Homepage from '@/pages/home/Home.vue'
    
    Vue.use(Router)
    
    export default new Router({
      routes: [
        {
          path: '/',
          name: 'Homepage',
          component: Homepage
        },
      ],
      mode: 'history',
      base: '/'
    })
    

    main.js:

    import Vue from 'vue'
    import App from './App.vue'
    import router from './router' //import the router
    
    new Vue({
      el: '#app',
      router, //use it in vue instance
      template: '<App/>',
      components: { App }
    })
    

    And you will have access to all components to use:

    this.$router.push({path: '/yourPath'})
    

    Note that you can also use names for your routes and call them by name like:

      routes: [
        {
          path: '/myPath',
          name: 'myPath',
          component: cmp
        }
      ]
    

    Then call the route in your component like this:

    this.$router.push({name: 'myPath'})
    

    For more take a look at named routes