node js sql, multple update column didnt change the data - mysql

i am trying to update data in mydatabase using Update the code work but the data didnt change
here is my controller code of the update function
const updateFasilitas = (req, res) => {
const idFasilitas = req.params.idFasilitas;
const idGedung = req.body.idGedung;
const namaFasilitas = req.body.namaFasilitas;
const linkTour = req.body.linkTour;
const penjelasan = req.body.penjelasan;
const sqlQuery = " UPDATE fasilitas SET idGedung = ?, namaFasilitas = ?, linkTour = ?, penjelasan = ? WHERE idFasilitas = ?";
db.query(sqlQuery, [idFasilitas ,idGedung, namaFasilitas, linkTour,penjelasan], (err, result) => {
if (err) {
console.log(err);
} else {
console.log(result);
}
});
};
here is my route code
router.put('/fasilitas/update/:idFasilitas', ctrl.updateFasilitas);
and the index
const { db } = require('./db');
const express = require('express');
const bodyParser = require('body-parser')
const cors = require('cors');
const cookieParser = require("cookie-parser");
const sessions = require('express-session');
const app = express();
const fasilitasroute = require ('./fasilitasroute');
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname));
app.use(cookieParser());
app.use(fasilitasroute);
app.listen(3000, () => {
console.log('server berhasil berjalan pada port 3000!');
});
i did try change the route to post but it didnt work as well. and the sql code i did try change by following some answer in this site from another question closely as me but it didnt work.
any idea how this happen?

Related

images not showing when using node js with handlebars(.hbs)

I have tried to search for an answer here but nothing so far worked, not many threads about handlebars.
I am struggling to get images to show up on my node app.
I have this on app.js and below that the code i am trying to get image to show up on the .hbs file:
const express = require("express");
const path = require("path");
const hbs = require("hbs");
const app = express();
const bodyParser = require("body-parser");
const port = process.env.PORT || 80;
require("./db/conn");
const SwimmingCollection = require("./models/schema");
const static_path = path.join(__dirname, "../public");
const template_path = path.join(__dirname, "../templates/views");
const partials_path = path.join(__dirname, "../templates/partials");
app.use(express.static(static_path));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({ extended: true }));
app.set("view engine", "hbs");
app.set("views", template_path);
hbs.registerPartials(partials_path);
app.get("/", (req, res) => {
res.render("index");
});
app.listen(port, () => {
console.log(`Listening to the port at ${port}`);
});
How to fix this issue?
Try below line for Static Path.
app.use(express.static(path.join(__dirname, 'public')))
https://expressjs.com/en/starter/static-files.html

CSS Style issue using Express.js

const express = require("express");
const bodyParser = require("body-parser");
const request= require("request");
const app = express();
var path = require("path");
app.use("/fonts", express.static(path.join("fonts")));
app.use("/images" , express.static(path.join("images")));
app.use("/css", express.static(__dirname + '/css.main.css'));
app.get("/", function(req,res){
res.sendFile(path.join(__dirname, '../', 'index.html'));
});
app.listen(3000, function(){
console.log("server is up and running")
})
Here, I can't seem to find a solution to this problem. My CSS and fonts and images are not working.

Nodejs Expess Script Unable to Create the Mysql Database Table

I created node js express applications with express generator. I am trying to create table by executing database script called db.js . This script is located into database folder . I am able to run the server but when I tried to execute the script by using C:\Users\Khundokar Nirjor\Desktop\Nodejs Resources\shopping-cart\database>node db.js
C:\Users\Khundokar Nirjor\Desktop\Nodejs Resources\shopping-cart\database>
It is not able to create the table or inserting records.
Here is my app.js code .
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var expressHbs = require('express-handlebars');
var mysql = require('./database/db');
var app = express();
require('./database/db');
// view engine setup
app.engine('.hbs',expressHbs({defaultLayout: 'layout' , extname: '.hbs'}));
app.set('view engine', '.hbs');
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('/', indexRouter);
//app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Here is the db.js code .
var mysql = require('mysql');
//var app = express();
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "shopdb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "CREATE TABLE products (imagepath VARCHAR(255), tittle VARCHAR(255), descriptions VARCHAR(255),price VARCHAR(255))";
var sql1 = "INSERT INTO products (imagepath, tittle,descriptions,price) VALUES ?";
var values = [
['https://upload.wikimedia.org/wikipedia/en/5/5e/Gothiccover.png', 'Gothic Veido Game','Awesome Game !!!!','25'],
['https://upload.wikimedia.org/wikipedia/en/5/5e/Gothiccover.png', 'Gothic Veido Game','Awesome Game old !!!!','100'],
['https://upload.wikimedia.org/wikipedia/en/5/5e/Gothiccover.png', 'Gothic Veido Game','Awesome Game New !!!!','120'],
['https://upload.wikimedia.org/wikipedia/en/5/5e/Gothiccover.png', 'Gothic Veido Game','Awesome Game !!!!','26'],
];
con.query(sql, sql1,[values], function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
});
con.destroy();
You should enable multistatement true while creating a connection as you are running multiple statements.change your configuration options as below:
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "shopdb",
multipleStatements: true
});
Refer this :
https://github.com/mysqljs/mysql#multiple-statement-queries

how to set index.html to another page, not homepage

I want to show index.html on special page '/chess', not on home page '/'.
Simple
app.get('/chess', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
doesn't work.
I get the below error
To create more of the "game center" try the approach of making realchess a router that gets imported to the main app.js
below is how I was able to achieve the desired result
rename app.js to chess.js
chess.js
var express = require('express');
var app = express();
app.use(express.static('public'));
app.use(express.static('dashboard'));
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
... rest of code ...
http.listen(port, function() {
console.log('listening on *: ' + port);
});
becomes
module.exports = function(server){
var express = require('express');
var app = express.Router();
app.use(express.static('public'));
app.use(express.static('dashboard'));
var io = require('socket.io')(server);
... rest of code ...
return app;
}
remove lines 145-147 and add module.exports = app;
create a new app.js
const express = require("express");
const app = express();
const http = require('http').Server(app);
const chess = require("./chess")(http);
const port = process.env.PORT || 3000;
app
.get("/", (req, res) => {
res.sendFile(__dirname + "/public/selector.html");
})
.use("/", express.static("public"))
.use("/chess",chess);
http.listen(port, function () {
console.log('listening on *: ' + port);
});
this will mound the chess router on the /chess directory, and allow you to mount a selector.html at /. Following a similar patter you could mount other games
Don't forget to declare the public director using use method.
app.use(express.static(__dirname + '/public'));
Using the code below i was able to remap
route '/chess' to serve index.html,
And
route '/' to serve select.html.
const express = require("express");
const app = express();
app
.get("/", (req, res)=>{
res.sendFile(__dirname + "/public/select.html");
})
.get("/chess", (req, res)=>{
res.sendFile(__dirname + "/public/index.html");
});
app.listen(3000, () => console.log("Example app listening on port 3000!"));
Can you post more of you application to see if there is another problem?

How to start a session when user logs in and end session when user logs out

I am new to node.js. How should I start a session when the user logs in and end the session when the user logs out?
Please note the environment of this application:
I'm using Windows
NPM, Express
MySQL for Node
This is my app.js file:
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var customers = require('./routes/customers');
var app = express();
var connection = require('express-myconnection');
var mysql = require('mysql');
app.set('port', process.env.PORT || 4300);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.use(
connection(mysql,{
host: 'localhost',
user: 'root',
password : '',
//port : 3306, //port mysql
database:'nodejs'
},'pool') //or single
);
app.get('/', customers.login);
app.get('/login', customers.login);
app.post('/login', customers.checklogin);
app.get('/logout', customers.logout);
app.use(app.router);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
And this is routing File (customers.js):
exports.logout = function(req, res){
var messages = '';
res.render('login',{page_title:"Login",message: messages});
};
exports.checklogin = function(req,res){
var loginInput = JSON.parse(JSON.stringify(req.body));
req.getConnection(function (err, connection) {
var username = loginInput.username;
var pswd = loginInput.pswd;
var query = connection.query("SELECT * FROM users WHERE username = ? AND pswd = ? ",[username,pswd], function(err,rows)
{
var messages = 'Username/Password is wrong. Try again.';
res.render('login',{page_title:"Login",message: messages});
});
});
};
It's really simple if you're using sessions.
app.post('/login', function(req, res, next) {
if(err) return next(err)
if(authenticate(req.body.username, req.body.password) req.session.user = {login: true, username: req.body.username }
res.render(<Some file you want to send to user>);
}
app.get('/logout', function(req, res, next) {
if(err) return next(err)
req.session.user = {login: false, username = null}
res.render(<Some file you want to send to user>);
This way you can login a user and set their username for later use in sessions and log them out in the same way.