PostgreSQL \ Vue - Not able to get data from the Database (PostgreSQL) using Express and Vue on Front-End

910 Views Asked by At

This is What I am getting on the Console of Chrome

I am Using Vue.js (vue-resource) and Express with PostgreSQL

I have a list on the server Side which I want to get on the items (and display on the Webpage) but I am not getting anything

Following is the Vue file code

<script>
export default {
  name: 'order',
  data () {
    return {
      orderOpt: 'Deliver',
      orderType: 'State',
      items: []
    }
  },
  created () {
    this.$http.get('localhost:3000/items').then(response => {
      this.items = response.body
    }, response => {
      setTimeout(function () {
        alert('The Server is not Running/items')
      }, 10000)
    })
  },
  computed: {
    total () {
      let sum = 0
      for (let i = 0; i < this.items.length; i++) {
        sum += parseInt(this.items[i].quantity)
      }
      return sum
    }
  },
  methods: {
    itemsUpdate (value) {
      this.items.forEach((item, i) => {
        console.log(value)
        item.inStock -= item.quantity
        item.quantity = 0
      })
      this.post(this.items)
    },
    post (Data) {
      this.$http.post('localhost:3000', Data)
    }
  },
  watch: {
  }
}
</script>


As I am using Express on the server side


This following code is present in the index.js

const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const cors = require('cors')


const app = express();
const Joi = require('joi');
const Data = require('./Data.json');
const { Pool, Client } = require('pg');

const pool = require('./db');


const port = process.env.USER || 3000;

//middleware
app.use(express.json());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(cors())

//DATA
const getItems = (req, res) => {
  pool.query('SELECT * FROM data', (err, results) => {
    if (err) {
      throw err
    }
    res.status(200).json(results.rows)
  })
}


app.listen(port, function () {
  console.log(`Server Starts on ${port}`);
});

//Requests
app.get('/', (req, res) => {
  res.json({Welcome: 'API Created'})
})

app.get('/item', async (req, res) => {
  res.status(200).send(Data);
});

app.get('/items', getItems)

app.post('/items', (req, res) => {
  try {
    const items = [req.body.name, req.body.inStock, req.body.quantity];
    const newItems = pool.query(
      "INSERT INTO data VALUES ($1, $2, $3) RETURNING *",
      items
    ).then(()=> {
      console.log(newItems);
    });
  } catch (e) {
    console.error(e);
  }
  pool.end();
});



0

There are 0 best solutions below