I am trying to basically call the 'get' method from html/ejs when a button is pressed to query the database and display the results. Sorry if it's very simple, but I just can't get it work.
I tried to require
the file and call the function inside a script
tag but that doesn't work on the browser. I tried to add the js file with a <script src="text/javascript" src="filename">
but that also results in errors.
The rest API I built talks to oracle 11g (Toad) using oracledb
.
I am basically trying to call the get
function in this class
const employees = require('../db_apis/employees.js');
async function get(req, res, next) {
try {
const context = {};
context.id = parseInt(req.params.id, 10);
const rows = await employees.find(context);
if (req.params.id) {
if (rows.length === 1) {
res.status(200).json(rows[0]);
} else {
res.status(404).end();
}
} else {
res.status(200).json(rows);
}
} catch (err) {
next(err);
}
}
...
db_apis/employees.js
const oracledb = require('oracledb');
const database = require('../services/database');
async function find(context) {
const baseQuery =
`SELECT *
FROM choice_names`;
console.log('in find');
let query = baseQuery;
const binds = {};
let additionalQuery = '\nwhere ';
if (context.id) {
binds.choice_name = context.id;
additionalQuery += `choice_name = :choice_name`;
// query += `\nwhere choice_name = :choice_name`;
} else if (context.user) {
binds.choice_user = context.user;
additionalQuery += `choice_user = :choice_user`;
} else if (context.date) {
binds.choice_date = context.date;
additionalQuery += `choice_date = :choice_date`;
}
if (context.id || context.user || context.date) {
query += additionalQuery;
}
console.log(query);
const result = await database.simpleExecute(query, binds);
return result.rows;
}
...
router.js
const express = require('express');
const router = new express.Router();
const employees = require('../controllers/employees');
router.route('/employees/:id?')
.get(employees.get)
.post(employees.post)
.put(employees.put)
.delete(employees.delete);
module.exports = router;
index.ejs
...
<button onclick="get()">Click me</button>
...