Passing MySQL data to HTML Select List - mysql

I need some assistance in passing the MYSQL query results to an HTML select list. I was able to pass some data from a JSON list from here - http://jsonplaceholder.typicode.com/todos, but am unable to pass my own data that is sent to localhost:7002/getJson. Is it a formatting thing, please take a look at my code and data and see what can be changed. Thanks!
route.js
module.exports = function(app, passport) {
app.get('/', function(req, res){
res.render('index.ejs');
});
app.get('/login', function(req, res){
res.render('login.ejs', {message:req.flash('loginMessage')});
});
app.post('/login', passport.authenticate('local-login', {
successRedirect: '/profile',
failureRedirect: '/login',
failureFlash: true
}),
function(req, res){
if(req.body.remember){
req.session.cookie.maxAge = 1000 * 60 * 3;
}else{
req.session.cookie.expires = false;
}
res.redirect('/');
});
app.get('/signup', function(req, res){
res.render('signup.ejs', {message: req.flash('signupMessage')});
});
app.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/profile',
failureRedirect: '/signup',
failureFlash: true
}));
app.get('/profile', isLoggedIn, function(req, res){
res.render('profile.ejs', {
user:req.user
});
});
app.get('/logout', function(req,res){
req.logout();
res.redirect('/');
})
//-SQL QUERY
var express = require('express')
, http = require('http')
, mysql = require('mysql'); // <---- HERE
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: "password",
database: 'testdb'
});
connection.connect(); // <---- AND HERE
// all environments
app.set('port', process.env.PORT || 7002);
app.get('/getJson',function(req,res){
connection.query('SELECT * FROM testtable', function(err, result, fields){
if(err) {
console.log(err);
res.json({"error":true});
}
else {
// console.log(result);
console.log(JSON.stringify(result));
res.json(result);
}
});
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
};
//-SQL QUERY END
function isLoggedIn(req, res, next){
if(req.isAuthenticated())
return next();
res.redirect('/');
}
signup.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>Login Register</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
<style>
html{
padding:50px;
}
</style>
</head>
<body>
<div class="container">
<div class="col-sm-6 col-sm-offset-3">
<h2>Register</h2>
<% if(message.length > 0) { %>
<div class="alert alert-danger"><%= message %></div>
<% } %>
<form action="/signup" method="post">
<script>
fetch('http://localhost:7002/getJson')
.then(response => response.json())
.then(json => {
console.log(json);
let select = document.getElementById("test");
json.forEach(e=>{
var opt1 = document.createElement("option");
opt1.text = e.title;
opt1.value = e.id;
select.add(opt1);
});
})</script>
<script>
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json())
.then(json => {
// console.log(json);
let select = document.getElementById("hi");
json.forEach(e=>{
var opt1 = document.createElement("option");
opt1.text = e.title;
// opt1.value = e.id;
select.add(opt1);
});
})</script>
<div class="form-group">
<select id="test">
</select><br>
<select id="hi">
</select><br>
</div>
<button type="submit" class="btn btn-succcess btn-lg">Register</button>
</form>
<hr>
<p>Need an account Register</p>
<p>Go Back Home.</p>
</div>
</div>
</body>
</html>
from: http://localhost:7002/getJson
from: http://localhost:8080/signup
from console

Your request is being blocked by CORS (Cross Origin Resource Sharing) policies, because your hosts are different (localhost:8080 and localhost:7002) and there is no Access-Control-Allow-Origin header in the responde from the express server.
You can add support to CORS from the origin site (localhost:8000) adding some HTTP headers to the express server:
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "localhost:8000"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});

Related

SyntaxError: missing ) after argument list in c:/.../list.ejs while compiling ejs

I am a beginner who is studying programming hard. SyntaxError: missing) after argument list in c://.../list.ejs while compiling ejs error but I don't know the solution. I want to get help from someone who is good at programming. Please help me.
This is server.js
const express = require('express');
const app = express();
const port = 8080;
const fs = require('fs');
const ejs = require('ejs');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: false
}));
app.listen(port, () =>{
console.log('서버가 실행됩니다.');
});
// maria db와 연결, test
const db = require('./db');
const { result } = require('lodash');
const { setEngine } = require('crypto');
db.query('SELECT now() AS time', function(err, rows, fields) {
if (err) throw err;
console.log('The time is: ', rows[0].time);
});
db.end();
// ejs를 통해서 html을 불러오는데 css까지 같이 불러옴
app.set('view engine', 'ejs');
//app.set('views', './crud/views');
app.engine('html', require('ejs').renderFile);
// 정적 파일 서비스
app.use(express.static('public'));
app.use(express.static('views'));
// html 파일을 불러오는 작업
app.get('/', (req, res) => {
res.render('list.ejs');
});
// 게시판에 사용자가 작성한 데이터를 db와 통신
app.get('/', function (req, res) {
fs.readFile('list.ejs', 'utf8', function (err, data) {
db.query('select * from user', function (err, results) {
if (err) {
res.send(err)
} else {
res.send(ejs.render(data, {
data: results
}))
}
})
})
})
app.get('/delete/:id', function (req, res) {
db.query('delete from user where id=?', [req.params.id], function () {
res.redirect('/')
})
})
app.get('/write', function (req, res) {
fs.readFile('write.html', 'utf8', function (err, data) {
res.send(data)
})
})
app.post('/write', function (req, res) {
const body = req.body
db.query('insert into user (title, name, content) values (?, ?, ?);', [
body.title,
body.name,
body.date,
body.howmanyseen,
body.content
], function() {
res.redirect('/')
});
});
app.get('/edit/:id', function (req, res) {
fs.readFile('edit.ejs', 'utf8', function (err, data) {
db.query('select * from user where id = ?', [req.params.id], function (err, result) {
res.send(ejs.render(data, {
data: result[0]
}))
})
})
})
app.post('/edit/:id', function (req, res) {
const body = req.body
db.query('update user SET title=?, name=?, content=? where id=?',[
body.title, body.name, body.content, req.params.id
], function () {
res.redirect('/')
})
})
This is db.js
var mysql = require('mysql');
var db = mysql.createConnection({
    host :'localhost',
    user :'root',
    password :'password',
    database :'express_db'
});
db.connect();
module.exports = db;`
This is list.ejs
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>공지사항</title>
<link rel="stylesheet" href="../css/css.css">
</head>
<body>
<% data.forEach(function (item, index) { %>
<div class="board_wrap">
<div class="board_title">
<strong>게시판</strong>
<p>예쁜놈으로다가 하나 긁어왔습니다!</p>
</div>
<div class="board_list_wrap">
<div class="board_list">
<div class="top">
<div class="num">번호</div>
<div class="title">제목</div>
<div class="writer">글쓴이</div>
<div class="date">작성일</div>
<div class="count">조회</div>
<div class="delete">삭제</div>
</div>
<div>
<div class="num"><%= item.id %></div>
<div class="title"><%= item.title %></div>
<div class="writer"><%= item.name %></div>
<div class="date"><%= item.date %></div>
<div class="count"><%= item.howmanyseen %></div>
DELETE
</div>
</div>
</div>
<div class="board_page">
<<
<
1
2
3
4
5
>
>>
</div>
<div class="bt_wrap">
등록
<!--수정-->
</div>
</div>
</div>
<% }); %>
</body>
</html>
I googled, but I couldn't find the right cause for this error because I saw different posts.
We are making a bulletin board through various trials and errors, and the goal is to have the bulletin board appear through the server and save it in the db once you enter the data.
perharps you have a title in your database that has a "(" character ?
by the way the line <%= item.title %> seems strange. Are you sure you want an hyperlink on view.html with empty text ?
be careful, you need to escape special characters in html (or xml ).

NodeJs Try to evaluate a HTML Form

I've an problem with evaluating an HTML Form using NodeJs and express.
This is my Java Script Code
My goal is to handle HTML Form in nodeJs using express.
const express = require('express');
const http = require('http');
const fs = require('fs');
const app = express();
var warehouses = [];
app.use(express.urlencoded({extended: true}));
app.use("/warehouse", (req, res, next) => {
fs.readFile("./addWarehouse.html", function(err, data) {
res.write(data);
next();
});
});
app.post("/warehouse/add", (req, res) => {
console.log("ADDED");
// warehouses.push(req.body.nWarehouse);
console.log('Request Type:', req.method);
res.end;
});
app.listen(8080);
And this is my HTML Form
<!DOCTYPE html>
<!-- <head>
<meta charset="utf-8" />
<title>Coole Seite</title>
</head> -->
<body>
<h1>Warehouses</h1>
<form method='POST' action="/warehouse/add">
<input type="text" name="nWarehouse" id="nWarehouse"/>
<input typse="submit" value="bitte sende" />
</form>
</body>
</html>
I tried to debug it with the console output and I figured out that it never access the app.use("/submit/add/" ... " part.
I would be happy to get some advice.
Here if the intent is to evaluate the form that is there in addWarehouse.html which should render when you go to /warehouse and the form should submit to /warehouse/add.
The middleware concept used via app.use(...) here is not required at all.
Express code:
const express = require('express');
const http = require('http');
const fs = require('fs');
const app = express();
var warehouses = [];
app.use(express.urlencoded({extended: true}));
//show addWareHouse.html for /warehouse
/* serving the HTML via fs */
app.get("/warehouse", (req, res, next) => {
fs.readFile("./addWarehouse.html", function(err, data) {
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
res.end();
});
//add warehouse form submit for /warehouse/add
app.post("/warehouse/add", (req, res) => {
console.log("ADDED");
console.log("REQUEST PARAM::", req.body);
//do you adding of ware-house stuff here
console.log("Request Type:", req.method);
return res.end();
});
app.listen(8080, () => console.log(`app listening on port 8080!`));
Note:
There are other handy ways to serve views (HTML) in express like template engines, res.sendFile() etc.

Sending HTML template through mail using node js node mailer

I had written node mailer code from w3schools. I want to send the html template designed (index.html in my case). Below is the code. please help me how can i send html template to the mail using node js.
var nodemailer = require('nodemailer');
var data = require('index.html');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'youremail#gmail.com',
pass: 'yourpassword'
}
});
var mailOptions = {
from: 'youremail#gmail.com',
to: 'myfriend#yahoo.com',
subject: 'Sending Email using Node.js',
html: 'data'
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
This is the right way of passing html in the nodemailer
var nodemailer = require('nodemailer');
var fs = require('fs');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'youremail#gmail.com',
pass: 'yourpassword'
}
});
fs.readFile('index.html', {encoding: 'utf-8'}, function (err, html) {
if (err) {
console.log(err);
} else {
var mailOptions = {
from: 'youremail#gmail.com',
to: 'myfriend#yahoo.com',
subject: 'Sending Email using Node.js',
html: html
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
}
});
Index.html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Node js Email </title>
<link rel="stylesheet" href="">
</head>
<body>
<div class="container"><br />
<h1>Send Email</h1><br />
<form onsubmit="sentthis()" method="post">
<div class="divi">
<label for="to"></label>To:</label>
<input type="email" class="too" name="to">
</div>
<div class="divi">
<label for="subject">Subject:</label>
<input type="text" class="subjectt" name="subject">
</div>
<div class="divi">
<p>Body:</p>
<textarea cols="" rows="5"class="textarea" name="body"></textarea>
</div>
<div class="divi">
<button type="submit" class="btn">Send</button>
</div>
</form>
</div>
</body>
</html>
server.js file
var express = require('express'),
path = require('path'),
nodeMailer = require('nodemailer'),
bodyParser = require('body-parser');
var app = express();
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var port = 3000;
app.get('/', function (req, res) {
res.render('index.html');
});
app.post('/sent',function(req,res){
let transporter = nodeMailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: 'marcus251#gmail.com',
pass: 'yourpassword'
}
});
let mailOptions = {
from: '"Marcus coffee" <marcus251#gmail.com>',
to: "Receiver Name <receiver#email.com>",
subject: req.body.subject,
text: req.body.body,
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: ', info.messageId, info.response);
res.render('index.html');
});
});
app.listen(port, function(){
console.log('Server is running at port: ',port);
});
This will solve your problem.

node js getting the image from the mysql and show in html page

this is my html code for getting an image from the mysql database table
<html ng-app="imgApp">
<head>
<title></title>
<script type="text/javascript" src="public/javascripts/angular.js"></script>
<script type="text/javascript" src="public/javascripts/imgController.js"></script>
</head>
<body ng-controller="imgController">
<img data-ng-repeat="data:image/png;base64,{{base64String}}">
<p>{{variable}}</p>
<button ng-click="getImageFunc()">Get data</button>
</body>
</html>
my backend server.js code
is given below i cant get my image in html page .
kindly check this code and correct the errors.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(express.static(__dirname));
app.use(bodyParser.json());
var mysql = require('mysql')
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'vinoth',
database: 'test'
})
connection.connect(function(err) {
if (err) throw err
console.log('You are now connected...')
})
app.get('/getimage',function(request,response){
connection.query ('select img from pic ',function(err,result){
console.log(result);
response.send(result);
});
})
app.listen(4000);
console.log("sever listening at port 4000");
Try to set content-type: image/jpeg or image/gif depends on type
app.get('/getimage', function(request, response) {
connection.query('select img from pic ', function(err, result) {
response.writeHead(200, {
'Content-Type': 'image/jpeg'
});
response.send(result); // Send the image to the browser.
});
});

How to make multy queries on mysql with node.js

I'm trying to run 2 queries against a MySQL database and they are not working. And display it, getting errors, can I do this a better way? I'm mainly asking how to display it in the home.handlebars file and how to make more than 1 query from MySQL database.
var express = require('express');
var handlebars = require('express-handlebars');
var bodyParser = require('body-parser')
var mysql = require('mysql');
var app = express();
app.engine('handlebars', handlebars({defaultLayout: 'main'}));
app.set('views', __dirname + '/views');
app.set('view engine', 'handlebars');
app.use(express.static('public'));
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'translation_project'
});
connection.connect();
app.get('/', function(req, res) {
var translatorid = 45;
var sqlQuery = "SELECT title,type FROM itemtable;"
connection.query(sqlQuery,function(err,rows,fields){
if(err){
console.log('Error'+err);
}else{
res.render('home',{items:rows}); // to be displayed in the home page
}
});
var sqlQuery2 = "SELECT dateoftranslation FROM translateditems;"
connection.query(sqlQuery2,function(err,rows,fields){
if(err){
console.log('Error'+err);
}else{
res.render('home',{dates:rows}); // to be displayed in the home page
}
});
});
app.listen(3000, function() {
console.log('Server is running at port 3000');
});
and Here is the home.handlebars file
<h1> My Applied Items </h1>
{{#each items}} <!-- the items refreneced in the index page-->
<p>{{title}}</p>
<p>{{type}}</p>
{{/each}}
{{#each dates}} <!-- the dates refreneced in the index page-->
<p>{{dateoftranslation}}</p>
{{/each}}
and Here is the home.handlebars file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Users Profile</title>
</head>
<body>
<h1> Mohamed </h1>
{{{body}}}
</body>
</html>
I would consider using Promises so you can wait for both queries to return before sending the result to the client:
function query(sqlQuery) {
return new Promise(function (resolve, reject) {
connection.query(sqlQuery, function (err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}
app.get('/', function (req, res) {
var query1 = query("SELECT title,type FROM itemtable;");
var query2 = query("SELECT dateoftranslation FROM translateditems;");
Promise.all(query1, query2).then(function (result) {
res.render('home', {
items: result[0],
dates: result[1]
});
});
});
You should do it in callback nesting due to asynchronous nature of connection.query().
app.get('/', function(req, res) {
var translatorid = 45;
var sqlQuery = "SELECT title,type FROM itemtable;",
sqlQuery2 = "SELECT dateoftranslation FROM translateditems;";
connection.query(sqlQuery,function(err,rows1){
if(err){
console.log('Error'+err);
}
else{
connection.query(sqlQuery2,function(err,rows2){
if(err){
console.log('Error'+err);
}
else{
res.render('home',{items:rows1,dates:rows2});
}
});
}
});
});
If you are performing several queries and you don't want Callback nesting(Due to non-readability of multi-nesting callbacks) then you should try promise or you can do that async way.
below is async way.
var async=require('async');
connection.connect();
app.get('/', function(req, res) {
var translatorid = 45;
var sqlQuery = "SELECT title,type FROM itemtable;",
sqlQuery2 = "SELECT dateoftranslation FROM translateditems;",
sqlQuery3="someQuery",
sqlQuery4="someOtherQuery",
sqlQuery5="someOtherOtherQuery";
async.parallel([function(cb){
connection.query(sqlQuery,function(err,rows1){
if(err){
console.log('Error'+err);
cb(err);
}
else{
cb(null,rows1);
}
});
},function(cb){
connection.query(sqlQuery2,function(err,rows2){
if(err){
console.log('Error'+err);
cb(err);
}
else{
cb(null,rows2);
}
});
},function(cb){
connection.query(sqlQuery3,function(err,rows3){
if(err){
console.log('Error'+err);
cb(err);
}
else{
cb(null,rows3);
}
});
},function(cb){
connection.query(sqlQuery4,function(err,rows4){
if(err){
console.log('Error'+err);
cb(err);
}
else{
cb(null,rows4);
}
});
},function(cb){
connection.query(sqlQuery5,function(err,rows5){
if(err){
console.log('Error'+err);
cb(err);
}
else{
cb(null,rows5);
}
});
}],function(err,results){
if(err){
// out of those 5 tasks at least one caused some error.
// handle that.
return;
}
// no error occurred.
var rows1=results[0],
rows2=results[1],
rows3=results[2],
rows4=results[3],
rows5=results[4];
res.render('home',{items:rows1,dates:rows2,other1:rows3,other2:rows4,other3:rows5});
});
});