I am new to node & express. I tried to create a sample API of note application.
When I tried to test API by creating a new note using POSTMAN, I am getting undefined as the value of req.body.title & req.body.content. But when I tried to console req.body I am getting the following:
{ '{"title": "Chemistry Note", "content": "Lorem ipsum note clasds"}': '' }
I am using latest version of express, bodyParser, mongoose.
This is the note.controller.js file
exports.create = (req, res) => {
console.log(req.body.title);
// Validating request
if(!req.body.content) {
return res.status(400).send({
message: "Note content cannot be empty"
});
}
// Creating a Note
const note = new Note({
title: req.body.title || "Untitled Note",
content: req.body.content
});
// Saving Note
note.save()
.then(data => {
res.send(data);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while creating the Note."
});
});
};
This is server.js file:
const express = require("express");
const bodyParser = require("body-parser");
// Creating Express Application
const app = express();
// Parse request of content-type - application/x-www-form-url-encoded
app.use(bodyParser.urlencoded({extended: true}));
// Parse request of content type - application/json
app.use(bodyParser.json());
const dbConfig = require("./config/database.config");
const mongoose = require("mongoose");
// Using native promises
mongoose.Promise = global.Promise;
// Connecting to Database
mongoose.connect(dbConfig.url, {
useNewUrlParser: true
}).then(() => {
console.log("Successfully connected to the database");
}).catch(err => {
console.log("Could not connect to the database. Exiting now...", err);
process.exit();
});
// Define a simple route
app.get('/', (req, res) => {
res.json({"message": "Welcome to Note Application"});
});
// Require Notes routes
require("./app/routes/note.routes.js")(app);
// Listen for requests
app.listen(3000, () => {
console.log("Listening on port 3000");
});
Below is note.model.js file:
const mongoose = require("mongoose");
// Defining Schema
const NoteSchema = mongoose.Schema({
title: String,
content: String
}, {
timestamps: true
});
// Creating Model with this schema
module.exports = mongoose.model('Note', NoteSchema);
Below is note.routes.js file:
module.exports = (app) => {
// Contains the methods for handling CRUD operations
const notes = require("../controllers/note.controller.js");
// Creating new Note
app.post('/notes', notes.create);
};
Please help, thank you. Any help would be appreciated.
{ '{"title": "Chemistry Note", "content": "Lorem ipsum note clasds"}': '' },
it's not a object you want.
For this json your key is '{"title": "Chemistry Note", "content": "Lorem ipsum note clasds"}'.
And its don't have any key like title, content.
Change above object to
{"title": "Chemistry Note", "content": "Lorem ipsum note clasds"}
Related
I am trying to use the Get method from the code below. I can use the Post method to post new instances to the database but my Get method is not working. When I tried to use the Get method I encountered the "AxiosError: Request failed with status code 404" error.
This is my code that contains the Get and Post methods:
const express = require('express');
const mongoose = require('mongoose');
const { ObjectId } = require('mongodb');
const { connectToDb, getDb, URI } = require('./db');
const Root = require('../models/Root');
const port = process.env.PORT || 7000;
const URL = 'http://localhost:7000'
const axios = require('axios');
// init & middleware
const app = express();
const router = express.Router();
app.use(express.json());
mongoose.set('strictQuery', false);
mongoose.set('bufferCommands', false);
let db
connectToDb((err) => {
if (!err) {
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
}
});
mongoose.connect(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// POST
app.post('/roots', async (req, res) => {
const { root_id, node_id, name } = req.body;
if (!root_id || !node_id || !name) {
return res
.status(400).send({ error: 'Please provide all required fields' });
}
const root = new Root({ root_id, node_id, name });
try {
const savedRoot = await root.save();
res.send(root);
} catch (err) {
//console.error('Error saving root:', err);
res.status(400).send(err);
}
});
// GET
app.get('/roots/:root_id', async (req, res) => {
try {
const response = await axios.get(
`${URL}/roots?filter={"where":{"root_id":${req.params.root_id}}}`
);
res.status(200).json(response.data);
} catch (err) {
console.error('Error getting root:', err);
res.status(400).send(err);
// res.status(500).json({ error: 'Could not fetch the root' });
}
});
// DELETE
app.delete('/roots/:root_id', async (req, res) => {
try {
await axios.delete(`${URL}/roots/${req.params.root_id}`);
res.status(200).json({ message: 'Root deleted successfully' });
} catch (err) {
console.error('Error getting root:', err);
res.status(400).send(err);
// res.status(500).json({ error: 'Could not delete the root' });
}
// Call to a method to delete all children nodes of the tree in the Node tables
});
// PATCH
app.patch('/roots/:root_id', async (req, res) => {
try {
const response = await axios.patch(
`${URL}/roots/${req.params.root_id}`,
req.body
);
res.status(200).json(response.data);
} catch (err) {
res.status(500).json({ error: 'Could not update the root' });
}
});
I use this code to connect to the database:
// Use this file to connect to database - easy to switch between local and cloud for testing
const{MongoClient} = require('mongodb')
let dbConnection
// Connect to local database
let URI = 'mongodb://127.0.0.1:27017/PM_AI'
module.exports = {
connectToDb: (cb) => {
MongoClient.connect(URI)
// MongoClient.connect(cloudURI)
.then((client) => {
dbConnection = client.db()
return cb()
})
.catch(err => {
console.log(err)
return cb(err)
})
},
getDb: () => dbConnection,
URI
}
ERROR LOG for the error that I encounter:
{
"message": "Request failed with status code 404",
"name": "AxiosError",
"stack": "AxiosError: Request failed with status code 404\n at settle (D:\\CSDS_395_Project\\AI-PM\\node_modules\\axios\\dist\\node\\axios.cjs:1900:12)\n at IncomingMessage.handleStreamEnd (D:\\CSDS_395_Project\\AI-PM\\node_modules\\axios\\dist\\node\\axios.cjs:2944:11)\n at IncomingMessage.emit (node:events:525:35)\n at endReadableNT (node:internal/streams/readable:1359:12)\n at process.processTicksAndRejections (node:internal/process/task_queues:82:21)",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"adapter": [
"xhr",
"http"
],
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"User-Agent": "axios/1.3.3",
"Accept-Encoding": "gzip, compress, deflate, br"
},
"method": "get",
"url": "http://localhost:7000/roots?filter={\"where\":{\"root_id\":1}}"
},
"code": "ERR_BAD_REQUEST",
"status": 404
}
The URL that I use to test my method in Postman is http://localhost:7000/roots/1.
Please let me know what am I doing wrong with my code here.
Thank you very much!
In your expressjs server file, the url you are using in mongoose.connect() refers to the expressjs server itself instead of localhost mongodb instance
So in your server.js/app.js or whatever is your main expressjs server file,
const MONGO_URL = 'mongodb://127.0.0.1:27017/PM_AI'
I can also see that you are using both mongo client and mongoose which I don't understand why... You only need one of these libaries to connect to mongodb from your backend
Also your code is pretty messed up so I've made the following changes
No need to use mongoose strict query and other configurations, simply using mongoose.connect() in latest mongoose version is enough. As mongodb connection establishes, you can launch your server
In terminal, write npm install dotenv. It is a package that is used to access variables in .env file, without it your server won't work properly
I've removed mongo client as it is not needed, simply using mongoose is enough
I don't know why you are making axios requests to your own server. This axios thing is what is causing 404 error. You should use axios only when you need to make api calls from frontend, or make api calls from your backend to some other backend server. For your own server, you should always prefer using a controller function for every route otherwise you will get 404 error. By controller function, I mean instead of axios.get, you need to execute mongoModel.delete() instead of axios.delete() or return mongoModel.findById() instead of axios.get()
For mongodb connection, use MONGO_URL and for connecting your own server, use URL
So the final version of your code should look like:
const express = require('express');
const mongoose = require('mongoose');
const { ObjectId } = require('mongodb');
const Root = require('../models/Root');
const MONGO_URL = 'mongodb://127.0.0.1:27017/PM_AI'
const axios = require('axios');
// For environmental variables in .env file
const dotenv = require("dotenv")
dotenv.config()
// init & middleware
const app = express();
const router = express.Router();
app.use(express.json());
const port = process.env.PORT || 7000
const URL = `http://localhost:${port}`
mongoose.connect(MONGO_URL).then(() => {
console.log("Mongodb connected")
app.listen(port,() =>
{console.log("Server started") }
});
// POST
app.post('/roots', async (req, res) => {
const { root_id, node_id, name } = req.body;
if (!root_id || !node_id || !name) {
return res
.status(400).send({ error: 'Please provide all required fields' });
}
const root = new Root({ root_id, node_id, name });
try {
const savedRoot = await root.save();
res.send(root);
} catch (err) {
//console.error('Error saving root:', err);
res.status(400).send(err);
}
});
// GET
app.get('/roots/:root_id', async (req, res) => {
try {
const response = await axios.get(
`${URL}/roots?filter={"where":{"root_id":${req.params.root_id}}}`
);
res.status(200).json(response.data);
} catch (err) {
console.error('Error getting root:', err);
res.status(400).send(err);
// res.status(500).json({ error: 'Could not fetch the root' });
}
});
// DELETE
app.delete('/roots/:root_id', async (req, res) => {
try {
await axios.delete(`${URL}/roots/${req.params.root_id}`);
res.status(200).json({ message: 'Root deleted successfully' });
} catch (err) {
console.error('Error getting root:', err);
res.status(400).send(err);
// res.status(500).json({ error: 'Could not delete the root' });
}
// Call to a method to delete all children nodes of the tree in the Node tables
});
// PATCH
app.patch('/roots/:root_id', async (req, res) => {
try {
const response = await axios.patch(
`${URL}/roots/${req.params.root_id}`,
req.body
);
res.status(200).json(response.data);
} catch (err) {
res.status(500).json({ error: 'Could not update the root' });
}
});
https://i.imgur.com/w5quRwA.jpg
I manually created a database called "shoppingitems" on the mongodb website console. I then created a model called "products" in an Express app and connected to the database. A collection called "products" was added to the "shoppingitems" database like I expected.
I then went to add a document to the "shoppingitems.products" collection, but instead an entirely new database called "test" was created, with a products collection and my submitted document in that 'test.products" collection instead of the "shoppingitems.products" collection like I intended.
Is there something wrong with my code? I make no mention of a "test" database anywhere, so IDK why it was created in the first place.
index.js
//Express
var express = require("express");
const app = express();
app.use(express.json());
//Mongoose
const dotenv = require("dotenv");
dotenv.config();
const mongoose = require("mongoose");
mongoose
.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("db connection succesfull"))
.catch((err) => console.log(err));
//CORS
const cors = require("cors");
app.use(cors());
//Routes
const productRoute = require("./routes/products");
app.use("/", productRoute);
//RUN INDEX.JS
app.listen(5000, () => {
console.log("backend server is running");
});
routes/products.js
var express = require("express");
var router = express.Router();
var Product = require("../models/Products");
/* GET PRODUCTS FOR HOMEPAGE */
router.get("/", async (req, res) => {
try {
productList = await Product.find();
res.json(productList);
} catch (error) {
console.log(error);
}
});
//POST PRODUCTS TO DATABASE
router.post("/", async (request, response) => {
console.log("request.body= ", request.body);
const newProduct = new Product(request.body);
try {
const savedProduct = await newProduct.save();
response.status(201).json(savedProduct);
} catch (err) {
response.status(500).json(err);
}
});
module.exports = router;
models/Products.js
const mongoose = require("mongoose");
const ProductSchema = new mongoose.Schema({
name: { type: String },
price: { type: Number },
description: { type: String },
image: { type: String },
stripeId: { type: String },
});
module.exports = mongoose.model("Product", ProductSchema);
Am I missing something? I don't see anything in the code that would be causing this and creating a "test" database. I've only used Mongo once or twice before though so I'm not exactly an expert. Can anybody here see what I'm doing wrong?
I'll post any additional code or information that you think is necessary to solving this. Just tell me what else you need to see.
test is the default database name used if you don't specify one. I also notice that nowhere in the code is a shoppingsitems database mentioned.
The connection string could contain the database name, but in this code that is taken from an environment variable.
I am trying to dynamically populate the WORD Document using npm docx. I am trying to read the data from the SQLite database but due to async node js property the values are not getting into the variable and it shows undefined. If I make the function synchronous the npm docx throws error and doesn't populate the document.
package.json
{
"name": "demoName",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"docx": "^5.1.1",
"express": "^4.17.1",
"md5": "^2.2.1",
"sqlite3": "^4.2.0"
}
}
index.js
const docx = require('docx');
var express = require('express');
var app = express();
var db = require("./database.js")
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const { AlignmentType, Document, Footer, Header, HeadingLevel, Packer, Paragraph, TextRun, UnderlineType, Table, TableCell, TableRow } = docx;
app.get("/doc", async(req, res) => {
var sql = "select * from DocDetails"
var params = []
//let DocDetailsData;
//let DocDetailsData = [{docId: "Some Doc Id"}];
const DocDetailsData = db.all(sql, params, (err, rows) => {
if (err) {
res.status(400).json({"error":err.message});
return;
}
console.log(rows[0]);
return rows[0];
});
console.log(DocDetailsData.docId);
const doc = new Document();
doc.addSection({
children: [
new Paragraph({
children: [
new TextRun({
text: "DEMO TEST DOCUMENT"
}),
new TextRun({
text: DocDetailsData.docId,
}),
]
}),
],
});
const b64string = await Packer.toBase64String(doc);
res.setHeader('Content-Disposition', 'attachment; filename=My Document.docx');
res.send(Buffer.from(b64string, 'base64'));
});
madeDoc = function(){
}
app.use(function(req, res){
res.status(404);
});
var server = app.listen(4041, function () {
var host = 'localhost'
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
database.js
var sqlite3 = require('sqlite3').verbose()
var md5 = require('md5')
const DBSOURCE = "db.sqlite"
let db = new sqlite3.Database(DBSOURCE, (err) => {
if (err) {
// Cannot open database
console.error(err.message)
throw err
}else{
console.log('Connected to the SQLite database.')
db.run(`CREATE TABLE DocDetails (
id INTEGER PRIMARY KEY,
docId text NOT NULL,
version float NULL,
editedBy text NULL,
editedDate text NULL,
effectiveDate text NULL)`,
(err) => {
if (err) {
// Table already created
console.log('Table not created');
}else{
console.log('Table created');
var insert = 'INSERT INTO DocDetails (docId, version, editedBy, editedDate, effectiveDate) VALUES (?,?,?,?,?)'
db.run(insert, ["NESS-RD-TEMP-EDCHB",2.1, "manab", "18-Jul-2017", "18-Jul-2020"])
}
})
}
});
module.exports = db
If you go to localhost:4041/doc, a word document should get downloaded but it shows only one row and not the data from database. I need the database value to be populated in the doc.
Thanks.
In order for this example to work, you need to understand how to work with asynchronous execution and callbacks. You cannot return anything from the callback and get it in the DocDetailsData variable as it would in synchronous code, because when you call the db.all method, the code continues to execute further, without waiting for the callback that you passed to it to work. Instead, you need to put the code for generating the doc file in the callback and do it in it. I hope that at least I could explain to you how it works. This is how your code will work correctly:
index.js
const docx = require('docx');
var express = require('express');
var app = express();
var db = require("./database.js")
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const { AlignmentType, Document, Footer, Header, HeadingLevel, Packer, Paragraph, TextRun, UnderlineType, Table, TableCell, TableRow } = docx;
app.get("/doc", async (req, res) => {
var sql = "select * from DocDetails"
var params = []
db.all(sql, params, async (err, rows) => {
if (err) {
res.status(400).json({"error":err.message});
return;
}
const DocDetailsData = rows[0];
const doc = new Document();
doc.addSection({
children: [
new Paragraph({
children: [
new TextRun({
text: "DEMO TEST DOCUMENT"
}),
new TextRun({
text: DocDetailsData.docId,
}),
]
}),
],
});
const b64string = await Packer.toBase64String(doc);
res.setHeader('Content-Disposition', 'attachment; filename=My Document.docx');
res.send(Buffer.from(b64string, 'base64'));
});
});
app.use(function(req, res){
res.status(404);
});
var server = app.listen(4041, function () {
var host = 'localhost'
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
});
database.js does not require changes
How do you implement MongoDB's Schema Validation feature in Express server? I'm working on a simple todo app and decided to use the native MongoClient instead of mongoose but i still do want to have a schema.
Base on MongoDB's docs here: https://docs.mongodb.com/manual/core/schema-validation/#schema-validation You can either create a collection with Schema or update an existing collection without schema to have one. The commands are run in the mongo shell, but how do you implement it in express?
So far what i did is make a function that returns the Schema Validation commands and call it on every routes but i get an error saying db.runCommand is not a function.
Here's my express server:
const express = require("express");
const MongoClient = require("mongodb").MongoClient;
const ObjectID = require("mongodb").ObjectID;
const dotenv = require('dotenv').config();
const todoRoutes = express.Router();
const cors = require("cors");
const path = require("path");
const port = process.env.PORT || 4000;
const dbName = process.env.DB_NAME;
let db;
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
MongoClient.connect(process.env.MONGO_URI,{useNewUrlParser: true},(err,client)=>{
if(err){
throw err;
console.log(`Unable to connect to the databse: ${err}`);
} else {
db = client.db(dbName);
console.log('Connected to the database');
}
});
/* Schema Validation Function */
const runDbSchemaValidation = function(){
return db.runCommand( {
collMod: "todos",
validator: { $jsonSchema: {
bsonType: "object",
required: [ "description", "responsible","priority", "completed" ],
properties: {
description: {
bsonType: "string",
description: "must be a string and is required"
},
responsibility: {
bsonType: "string",
description: "must be a string and is required"
},
priority: {
bsonType: "string",
description: "must be a string and is required"
},
completed: {
bsonType: "bool",
description: "must be a either true or false and is required"
}
}
} },
validationLevel: "strict"
} );
}
/* Get list of Todos */
todoRoutes.route('/').get((req,res)=>{
runDbSchemaValidation();
db.collection("todos").find({}).toArray((err,docs)=>{
if(err)
console.log(err);
else {
console.log(docs);
res.json(docs);
}
});
});
/* Get Single Todo */
todoRoutes.route('/:id').get((req,res)=>{
let todoID = req.params.id;
runDbSchemaValidation();
db.collection("todos").findOne({_id: ObjectID(todoID)}, (err,docs)=>{
if(err)
console.log(err);
else {
console.log(docs);
res.json(docs);
}
});
});
/* Create Todo */
todoRoutes.route('/create').post((req,res,next)=>{
const userInput = req.body;
runDbSchemaValidation();
db.collection("todos").insertOne({description:userInput.description,responsible:userInput.responsible,priority:userInput.priority,completed:false},(err,docs)=>{
if(err)
console.log(err);
else{
res.json(docs);
}
});
});
/* Edit todo */
todoRoutes.route('/edit/:id').get((req,res,next)=>{
let todoID = req.params.id;
runDbSchemaValidation();
db.collection("todos").findOne({_id: ObjectID(todoID)},(err,docs)=>{
if(err)
console.log(err);
else {
console.log(docs);
res.json(docs);
}
});
});
todoRoutes.route('/edit/:id').put((req,res,next)=>{
const todoID = req.params.id;
const userInput = req.body;
runDbSchemaValidation();
db.collection("todos").updateOne({_id: ObjectID(todoID)},{ $set:{ description: userInput.description, responsible: userInput.responsible, priority: userInput.priority, completed: userInput.completed }},{returnNewDocument:true},(err,docs)=>{
if(err)
console.log(err);
else
res.json(docs);
console.log(db.getPrimaryKey(todoID));
});
});
/* Delete todo */
todoRoutes.route('/:id').delete((req,res,next)=>{
const todoID = req.params.id;
runDbSchemaValidation();
db.collection("todos").deleteOne({_id: ObjectID(todoID)},(err,docs)=>{
if(err)
console.log(err)
else{
res.json(docs);
}
});
});
app.use('/todos',todoRoutes);
app.listen(port,()=>{
console.log(`Server listening to port ${port}`);
});
I also tried it on the initial client connection but i got the same error:
You validation schema will be added to the MongoDB driver when you run it for the first time. So you don't need to perform validation every time you run a query. You will get a validation response directly from the driver's validation schema that was added initially. Again you will not explicitly get to know which object is causing the error. The validation response will be more generic.
I have an existing postgresql database with Rails, now I'm making a Node.js app which is using the same database. I already have users in my db and now I would like to list them all.
I successfully created an express app and then I did as follows:
✗ npm install --save sequelize pg pg-hstore
✗ sequelize init
index.js
const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const pg = require('pg');
var conString = 'postgres://localhost:5432/db_name';
var client = new pg.Client(conString);
const app = express();
client.connect(err => {
if (err) {
console.error('connection error', err.stack);
} else {
console.log('connected');
}
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.send(models.User.findAll);
});
const PORT = process.env.PORT || 5000;
app.listen(PORT);
In my config.json I have:
"development": {
"username": "my_username",
"password": null,
"database": "database_name",
"host": "127.0.0.1",
"dialect": "postgres"
}
I get this error: UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()
I'm probably missing a big step but I don't know what it is, I have never done this before.
Example Query
const query = {
text: 'CREATE TABLE IF NOT EXISTS coverages ('+
'vaccine VARCHAR(64),' +
'country VARCHAR(255),' +
'region VARCHAR(255),' +
'year VARCHAR(4),' +
'value VARCHAR(12),' +
'PRIMARY KEY(vaccine, country, region, year, value))'
};
client.query(query)
.then(function(res) {
console.log(res);
})
.catch(function(err) {
console.log('\nError executing query', err.stack);
});
Here are some example queries using async / await (which requires Node 8+, I believe, so make sure your version supports this):
var express = require('express');
var pg = require('pg');
var router = express.Router();
let conString = 'postgres://localhost:5432/db_name';
var postgrespool = new pg.Pool({
connectionString: conString
});
router.get('/checkdbconnection', function(req, res, next) {
(async () => {
// Here is the query!
// alter it to query a table in your db
// this example just confirms a connection
var { rows } = await postgrespool.query(`
SELECT
'Hello from Postgres' AS pg_val;`);
if (rows.length) {
return res.send(rows);
} else {
res.status(404);
return res.send('No response from database.');
}
})().catch(e =>
setImmediate(() => {
res.status(500);
console.log(e);
return res.send('Error: ' + e.message);
})
);
});
router.get('/checkdbconnection/:name', function(req, res, next) {
let param_name = req.params.name;
(async () => {
// this example demonstrates how to pass parameters to your query with $1, $2, etc.
// usually, the cast of "::text" won't be necessary after the "$1"
var { rows } = await postgrespool.query(`
SELECT
'Hello from Postgres' AS pg_val,
$1::text AS parameter;`, [param_name]);
if (rows.length) {
return res.send(rows);
} else {
res.status(404);
return res.send('No response from database.');
}
})().catch(e =>
setImmediate(() => {
res.status(500);
console.log(e);
return res.send('Error: ' + e.message);
})
);
});
module.exports = router;
If you visit http://localhost:5000/checkdbconnection , you'll get this response:
[
{
"pg_val": "Hello from Postgres"
}
]
And if you visit, say, http://localhost:5000/checkdbconnection/Al-josh , you'll get this:
[
{
"pg_val": "Hello from Postgres",
"parameter": "Al-josh"
}
]
Hopefully my comments in the code have made it clear how the queries work, so you can alter them to your purpose. If not, provide some more detail about your tables and I can amend this answer.
Note also that I am using pg.Pool here to connect to Postgres. This is totally secondary to your question, but the documentation is worth reading.