ExpressJS: push query values in array and route to ejs - mysql

I need to get query values which will be routed to ejs file. I am able to do that using data:rows. However, this gives solution:Sandy. I only need Sandy. Below, I am pushing the values i.e. rows[i] using for loop into array arr, however, only the last element stays in the array. I tried using forEach loop which is giving syntax error. Any ideas/help would be highly appreciated!
main.js
const express = require('express')
const app = express()
var router = express.Router()
app.set('view engine', 'ejs');
var arr = [];
var mysql = require('mysql')
var connection = mysql.createConnection({
host : 'host',
port : 'port',
user : 'user',
password : 'password',
database : 'database'
});
connection.connect()
connection.query('SELECT customer_name as solution FROM customers', function (err, rows, fields) {
if (err) throw err
for(var i in rows){
arr.push[rows[i].solution];
}
app.get('/', function(req, res) {
res.render('index', {data:arr});
});
})
app.listen(3000, () => console.log('Example app listening on port 3000!'));
index.ejs
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<link rel="icon" href="images/favicon.png">
</head>
<body>
<<h1><%= data %></h1>
</body>
</html>

Your query should be executed when the users hit the / route, this way they will always receive updated data from the server, also there is no need to create another array, you can just pass the query result to ejs and then loop through it:
main.js
const express = require('express')
const app = express()
var mysql = require('mysql')
app.set('view engine', 'ejs');
var connection = mysql.createConnection({
host : 'host',
port : 'port',
user : 'user',
password : 'password',
database : 'database'
});
connection.connect();
app.get('/', function(req, res) {
connection.query('SELECT customer_name as solution FROM customers', function (err, rows, fields) {
if (err) throw err;
res.render('index', { data: rows });
});
});
index.ejs
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<link rel="icon" href="images/favicon.png">
</head>
<body>
<% for ( var i = 0; i < data.length; i++) { %>
<h1><% data[i].solution %></h1>
<% } %>
</body>
</html>

Related

Browser displays JSON response instead of HTML with JSON in network tab

I am following this video: https://youtu.be/5TxF9PQaq4U?t=600
When he makes a GET request to localhost:8383/info the JSON {info: "Text"} is shown inside the network-tab but the browser still displays the HTML page. When I make the GET request to localhost:8383/info, the browser displays the JSON but not the HTML. How can I get the same result as him?
Index.html (inside "public" folder)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="">
<input id="input" type="text">
<button id="get">Get</button>
</form>
</body>
<script>
const input = document.getElementById("input")
const getbtn = document.getElementById("get")
getbtn.addEventListener("click", getInfo);
async function getInfo(e) {
e.preventDefault()
const res = await fetch("http://localhost:8383/info", {method: "GET"})
console.log(res)
}
</script>
</html>
Server.js
const express = require("express")
const app = express()
const port = 8383
app.use(express.static("public"))
app.get("/info", (req, res) => {
res.status(200).json({info: "Text"})
})
app.listen(port, ( ) => console.log("Server started"))
This is what the browser displays on localhost:8383/info
I have tried to make the GET request to localhost:8383 (without info) but then the response is the HTML file, not {info: "Text"}.
You missed two places
#1 Need to add CORS in server.js
app.use(cors());
#2 Need to add DOM element in index.html and update it in script.
<p id="message">
The message will go here
</p>
...
document.getElementById('message').textContent = JSON.stringify(info);
This is full code.
const express = require("express")
const cors = require('cors');
const app = express()
const port = 8383
app.use(cors());
app.get("/info", (req, res) => {
res.status(200).json({info: "Text"})
})
app.listen(port, ( ) => console.log("Server started"))
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="">
<input id="input" type="text">
<button id="get">Get</button>
</form>
<p id="message">
The message will go here
</p>
</body>
<script>
const input = document.getElementById("input")
const getbtn = document.getElementById("get")
getbtn.addEventListener("click", getInfo);
async function getInfo() {
const response = await fetch('http://localhost:8383/info');
return await response.json();
}
getInfo().then(info => {
document.getElementById('message').textContent = JSON.stringify(info);
});
</script>
</html>
Result - ran GO Live extension in VS.code and node server.js

Getting form input using express then inserting to mysql database returns and inserts blank

(noob alert) Sup guys. I'm an extreme beginner and this will be my first question so I'd be grateful if someone could lend me a hand with this. I just started learning express today and I'm not sure yet where to put what but I'm pretty sure that's why this isn't working properly. It only returns message = "" and inserts a blank into the database instead of the message typed inside the textarea. Sorry for the noob question
const express = require('express')
const path = require('path')
const app = express()
const mysql = require("mysql")
const bodyParser = require('body-parser');
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "......",
database: "chat_database"
})
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "public")))
app.listen(3000)
app.post('/', (req, res) => {
const data = req.body.message
console.log(data);
let sql = `INSERT INTO chats(content) VALUES (?)`
connection.query(sql, [data], (err, result) => {
if (err) throw err
console.log(result);
console.log("data has been successfully inserted into the database!");
})
})
const mainChatBlock = document.querySelector("#main-chat-block")
const mainInputArea = document.querySelector("#main-input-area")
const mainSendButton = document.querySelector("#main-send-button")
mainSendButton.addEventListener("click", () => {
let newMessage = document.createElement("div")
newMessage.innerHTML = mainInputArea.value
mainChatBlock.append(newMessage)
mainInputArea.value = ""
mainChatBlock.scrollTop = mainChatBlock.scrollHeight
})
mainInputArea.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
mainSendButton.click();
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>my chat</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<main>
<div id="outermost-main-div">
<div id="outermost-chat-div">
<div id="main-chat-area">
<div id="main-chat-block">
</div>
</div>
<form action="/" method="post" id="outer-input-area">
<textarea name="message" id="main-input-area" placeholder=">>> Enter your message here"></textarea>
<button type="submit" id="main-send-button">Send</button>
</form>
</div>
</div>
</main>
<script src="script.js"></script>
</body>
</html>
I figured it out guys. turns out the culprit was the clear value in the client side js mainInputArea.value = ""
but to clear the entry, I did something like this
mainSendButton.addEventListener("click", () => {
let newMessage = document.createElement("div")
newMessage.innerHTML = mainInputArea.value
mainChatBlock.append(newMessage)
mainChatBlock.scrollTop = mainChatBlock.scrollHeight
setTimeout(del, 100)
})
function del() {
mainInputArea.value = ""
}

express-handlebars won't read html in main-layout expressjs

Greetings I have a problem with handlebars It won't read HTML in my file here is the screenshot of a problem with provided code. Folder structure is
views
layouts
main-layout.hbs
home.hbs
server.js
const express = require("express");
const session = require("express-session");
const bodyParser = require("body-parser");
const con = require("./database/dbConnect");
const bcrypt = require("bcrypt");
const validator = require("validator");
let app = express();
const hbs = require("express-handlebars");
let PORT = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static("public"));
app.engine('hbs', hbs.engine({ extname: 'hbs' }));
app.set('view engine', 'hbs');
app.set('views', './views');
app.get("/", (req, res) => {
res.render("home", {
layout: "main-layout",
title: "Login",
});
});
app.listen(PORT, (err) => {
if(err) console.log("Error Occured: ", err);
console.log("Server is running on port: http://localhost:"+ PORT);
});
main-layout.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{ title }}</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</head>
<body>
{{ body }}
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</body>
</html>
home.hbs
<h1>{{ title }}</h1>
<p>Welcome</p>
I found the solution to the problems it the
{{ body }}
It must be with 3 curly braces
{{{ body }}}

How to send a variable from nodejs file to ejs file

var express = require('express');
var app = express();
app.use("/", function(request, response){
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Test");
dbo.collection("users").find({}, { "name":"John" }).toArray(function(err, result) {
if (err) throw err;
console.log(result);
// res.sendFile(__dirname + "/views/index.ejs");
db.close();
});
});
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="./index.js"></script>
<title>Document</title>
</head>
<body>
<h1 id="result"><%=result%></h1>
</body>
</html>
I have 2 files and I want to use a variable from one file in another. How can I send the variable result from my nodejs file to my ejs file, in <h1 id="result"><%=result%></h1>?
In order to do that you have to use express res.render()
according to the docs
res.render(view [, locals] [, callback])
Renders a view and sends the rendered HTML string to the client. Optional parameters:
locals, an object whose properties define local variables for the view.
You should use something like this
res.render('index',{result});
then now you would be able to access that value you have sent over in your index.ejs file however I would advice you to explicitly declare in your application that you are using ejs so that you would not have to go through the struggles of re-stating ejs at the end of you code like before
at the top after this code var app = express()
you could say
app.set("view engine", "ejs");

Having trouble sending a json to html and getting <%- to work

So I'm trying to use values in my json file to display on the webpage. For instance, one value will be the text on the accordion button.
I'm using express and ejs, and I've been trying to use <%- %> to call the text in the json file but it won't seem to appear on the webpage.
index.js
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.get('/', function(req, res) {
res.locals.ClinNotes1=('.\ClinNotes.json');
res.render('webpage');
})
webpage.ejs
<div id="Problems" class="tabcontent">
<div class="problemItems">
<button class="accordion" id="accordionDis">
<span><ul><%-ClinNotes1.resourceType%></ul></span>
ClinNotes.json
{ "resourceType": "Bundle",
....}
If you want to show your JSON data on your webpage you can do something like that:
index.js
//here import your json file
const notes = require('./ClinNotes.json'); //suppose your file is in the root directory
app.get('/', function(req, res) {
res.render('webpage', {data: notes});
})
webpage.ejs
<span><ul><%-data.resourceType%></ul></span>
Hopefully, it might help you
Here is a quick example I put together.
Basically, you want to iterate over the JSON file the same way you would a Javascript object.
app.js
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
//Use EJS Templating Engine
app.set('view engine', 'ejs');
app.get('/', (req, res, next) => {
res.locals.dataFromJSON = require('./data.json');
res.render('index');
});
//Start Server
app.listen(port, () => {
console.log(`Server started on port number ${port}`);
});
index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Example</title>
</head>
<body>
<h1>Hope this helps!</h1>
<% Object.values(dataFromJSON).forEach((value) => { %>
<button><%= value %></button>
<% }); %>
</body>
</html>
data.json
{
"resourceType": "Bundle",
"resourceType2": "Bundle2",
"resourceType3": "Bundle3",
"resourceType4": "Bundle4"
}
Here is a gitub repo i created
Here is the expected output deployed to heroku
I hope this helps! 👍