Vue CRUD using NodeJs (MySql conncetion) - How do I get the data from server-side to client-side?

Viewed 1194

I'm trying to learn more about Vue and to make it interesting I have connected to my MySql-DB using nodeJS.

By following a tutorial (https://webdeasy.de/en/complete-login-system-with-node-js-vue-js-restapi-jwt-part-1-2/) I have a working Login system. Now I want to fetch some data from another table (the table called 'clients') and make a simple CRUD, but I do not understand how to get the data from the Server-side(node-js) to the Client-side(Vue).

I got a connection working where I can output my table data in the console.log - And I know I have use Axios (pointing to localhost:3000 where my server is running) to make it work, but everything I have tried either crashes my app or just doesn't work.

My router.js filer (Server-side) looks like this (I didn't paste all the login 'stuff' to keep clean for you):

// routes/router.js

const express = require('express');
const router = express.Router();

const bcrypt = require('bcryptjs');
const uuid = require('uuid');
const jwt = require('jsonwebtoken');

const db = require('../lib/db.js');
const userMiddleware = require('../middleware/users.js');

// All the login code is here
// All the login code is here
// All the login code is here


db.query
    ("SELECT * FROM clients", function (err, result, fields) {
        if (err) throw err;
        console.log(result);
});


module.exports = router;

Which correctly returns this in the console.log:

[nodemon] starting `node Server`
The server running on port 3000
[
  RowDataPacket {
    id: 1,
    name: 'Sample Client One',
    email: 'email-one@domain.com',
    phone: '12345678'
  },
  RowDataPacket {
    id: 3,
    name: 'Sample Client two',
    email: 'mail-two@domain.com',
    phone: '12345678'
  }

My Clients.vue looks like this now:

<template>
  <div>
    <h1>Hi {{ username }}, Welcome to Clients</h1>
    <p>{{ secretMessage }}</p>
  </div>
</template>
<script>
  import AuthService from '@/services/AuthService.js';


  export default {
    data() {
      return {
        secretMessage: 'Sample secret message',
        username: '',
      };
    },

    async created() {
      if (!this.$store.getters.isLoggedIn) {
        this.$router.push('/login');
      }
      this.username = this.$store.getters.getUser.username;
      this.secretMessage = await AuthService.getSecretContent();
    },
    methods: {
      logout() {
        this.$store.dispatch('logout');
        this.$router.push('/login');
      }
    }
  };

</script>

I have Axios installed, I just removed the import of it to avoid the error. As you probably can see a am new at this so let me know if going about this all wrong or if you need to see more of my code.

//Rue

1 Answers

Make sure that you are fetching the clients from an CRUD endpoint.

For instance, you can add a new /clients endpoint where you read all the clients then return them back to client-side with res.status(200).send(result), as follows:

router.get('/clients', (req, res, next) => {
    db.query("SELECT * FROM clients", function (err, result, fields) {
        if (err) {
          res.status(400).send();
          throw err;
        };

        console.log(result);
        res.status(200).send(result);
    });
});

And your client-side code now needs to fetch data from server-side. One can create a new file ClientServices.js under services/ folder, like so

// src/services/ClientServices.js

import axios from 'axios';
const url = 'http://localhost:3000/api/';
export default {
  getClients() {
    return axios
      .get(url + 'clients/')
      .then(response => response.data);
  }
};

The UI code now needs to import the new file and call getClients method and list them.

<template>
  <div>
    <h1>Hi {{ username }}, Welcome to Clients</h1>
    <p>{{ secretMessage }}</p>
  </div>
  <div :key="client.id" v-for="client in clients">
    <strong>client.name</strong>
    <small>client.email</small> | <small>client.phone</small>
  </div>
</template>
<script>
  import AuthService from '@/services/AuthService.js';
  import ClientService from '@/services/ClientService.js';


  export default {
    data() {
      return {
        secretMessage: 'Sample secret message',
        username: '',
        clients: [],
      };
    },

    async created() {
      if (!this.$store.getters.isLoggedIn) {
        this.$router.push('/login');
      }
      this.username = this.$store.getters.getUser.username;
      this.secretMessage = await AuthService.getSecretContent();

      var self = this
      ClientService.getClients().then((clients) => {
       self.clients = clients;
      });
    },
    methods: {
      logout() {
        this.$store.dispatch('logout');
        this.$router.push('/login');
      }
    }
  };

</script>
Related