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

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

Related

node js sql, multple update column didnt change the data

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?

I want to render imagefile in html. What should I do?

show my code in inputinfo.html and index.html
<...>
<table border="1">
<label for="image">image : </label><br>
<input type="image" name="image" src="inputtype.jpg" width="100" height="100" alt="ready"><br>
</table>
<....>
show my code in app.js
const express = require('express');
const app = express();
const bodyParser = require("body-parser");
const PORT = process.env.port || 8090;
const cors = require('cors');
const multer = require('multer');
const fs = require('fs');
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.use(express.static(__dirname + '/images'));
app.use('/', indexRouter);
app.use('/html', htmlRouter);
app.use('/to', toServer);
const server = app.listen(PORT, () => {
let dir = './uploadedFiles';
if(!fs.existsSync(dir))
fs.mkdirSync(dir);
console.log('Start server : ' + PORT);
});
I want to render image files in html.
in index.html, success render image.
but inputinfo.html, fail render image.
so, I change url
before
index.html -> localhost:8090/html,
inputinfo.html -> /localhost:8090/html/inputinfo
after
inputinfo.html -> localhost:8090/html,
index.html -> /localhost:8090/html/inputinfo
in inputinfo.html, success render image, why?????
I want to render image file in all html, what should I do?
I think I control source code in app.js, don't you? but I don't know how to control source code.

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.

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?

Upload file in Expressjs bodyParser

can I just upload some on file with Expressjs with bodyParser.json() middleware? I'm using Expressjs 4.14 and my app.js snipet is like this
require('dotenv').config();
require('./app/models/db');
var express = require('express');
var session = require('express-session');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
var socket_io = require("socket.io");
var io = socket_io();
app.io = io;
var mainRouteConfig = require('./app/routes/routes')(io);
// var notifRouteConfig = require('./app/routes/notif')(io);
// view engine setup
app.set('views', path.join(__dirname, 'app', 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(session({ secret: 'super-secret-code'}));
app.use('/', mainRouteConfig);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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');
});
// io.on("connection", function(socket){
// console.log( "A user connected" );
// });
module.exports = app;
I think the problem is in app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false })); when want upload some file using multipart/form-data
BodyParser is mainly used for urlencoded enctype.
For multipart I use Formidable and express-formidable.
npm install formidable express-formidable --save
Take a look at docs here
Good luck