Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 

README.md

JavaScript Example

Database

Start database container

docker compose up -d

Restore data

docker exec -i postgres psql -U postgres postgres < database.sql

Server

Node Version: 18.10

cd server
npx express-generator --no-view

Delete routes/index.js file.

Install libraries, database library and CORS library

cd server
npm install
npm install pg-promise
npm install cors

Update app.js to match below:

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors')

var usersRouter = require('./routes/users');

var app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors())

app.use('/users', usersRouter);

module.exports = app;

Update routes/users.js to match below to query database:

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

const pgp = require('pg-promise')(/* options */)
const db = pgp('postgres://postgres:postgres@localhost:5432/postgres')


/* GET users listing. */
router.get('/', function(req, res, next) {
  db.many('SELECT * FROM users')
  .then((data) => {
    res.json(data);
  })
  .catch((error) => {
    console.log('ERROR:', error)
  })
});

module.exports = router;

Start server:

cd server
npm run start

Open web browser and navigate to http://localhost:3000/users to receive this output:

[{"id":1,"name":"Russell Feldhausen","eid":"russfeld"},{"id":2,"name":"Nathan Bean","eid":"nhbean"},{"id":3,"name":"Josh Weese","eid":"weeser"}]

Client

Leave server running in a terminal and open another to work on client.

Create Vue 3 project:

 npm create vue@latest

Use "client" as the project name, accept all defaults.

Replace App.vue with the following:

<script setup>
import { ref } from 'vue';
const users = ref(null);
fetch('http://localhost:3000/users')
    .then(response => response.json())
    .then(data => users.value = data);
</script>

<template>
  <ul>
    <li v-for="user in users">{{ user.name }} ({{  user.eid }})</li>
  </ul>
</template>

Update build command in package.json to output to server folder:

"scripts": {
    "dev": "vite",
    "build": "vite build --emptyOutDir --outDir ../server/public",
    "preview": "vite preview"
  },

Start client:

cd client
npm install
npm run dev

Open the client at http://localhost:5173 in a webpage to see a list of users like the following:

  • Russell Feldhausen (russfeld)
  • Nathan Bean (nhbean)
  • Josh Weese (weeser)

If it works, build the client and restart the server:

cd client
npm run build
cd server
npm run start

You should now be able to visit http://localhost:3000 to see the frontend working correctly.