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

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.

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.

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

Node js express can't parse body after routes moved into own folder

Moved routes into their own folder now I cant parse the response body. Controller sends body correctly. App worked correctly when routes were in server js file.
Server.js BEFORE
var express = require('express');
var app = express();
var routes = require('./routes/routes.js');
app.use('/',routes);
app.use(express.static(__dirname + '/public'));
app.use('/bootstrap', express.static(__dirname + '/public/bower_components/bootstrap/dist'));
app.use('/jquery', express.static(__dirname + '/public/bower_components/jquery/dist'));
app.use('/angular', express.static(__dirname + '/public/bower_components/angular'));
app.use('/controllers', express.static(__dirname + '/public/controllers'));
Routes.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var ObjectId = require('mongojs').ObjectID;
var mongojs = require('mongojs');
var db = mongojs('contactlist',['contactlist'])
var router = express.Router();
app.use(bodyParser.json());
router.put('/contactlist/:id',function(req,res){
console.log("req.body.name");//gives undefined
db.contactlist.findAndModify({
query:{_id: ObjectId(req.params.id)},
update:{ $set:{name:req.body.name,email:req.body.email,number:req.body.number}},
new: true},
function(err,doc){
res.json(doc);
});
});
module.exports = router;
Also, any thoughts as to why I have to append routes.js here instead of just / routes?
var routes = require('./routes/routes.js');
Folder Structure
-App
node_mods/
public/
index.html
controllers/
resources/
routes/
routes.js
Server.js AFTER
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
var routes = require('./routes/routes.js');
app.use('/',routes);
app.use(express.static(__dirname + '/public')); //look for static files js html css etc
app.use('/bootstrap', express.static(__dirname + '/public/bower_components/bootstrap/dist'));
app.use('/jquery', express.static(__dirname + '/public/bower_components/jquery/dist'));
app.use('/angular', express.static(__dirname + '/public/bower_components/angular'));
app.use('/controllers', express.static(__dirname + '/public/controllers'));
app.listen(3000);
console.log('server running on port 3000');
As for your (second?) quetion , about importing requiring routes.js:
When you do
var routes = require('./routes/routes.js');
you're not calling the routes. You're, in fact requiring a module. That is not only routes data, but also the router object Behaviour, including associated middleware for some of all of the routes.
If you look carefully, your router.js exports the router "object" ( or function, call it as you want). So when you require it, you get the whole package, not only data
Your body is parsing after your route is called.
Pass your body-parser code in your main server file generally, it is server.js before all the routes.
Like this:
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));