Cannot GET /ejs file - html

I'm trying to get the stat of a survey page done with html
when I try to connect to the ejs view of the webpage it gives me Cannot GET /showResults
// Entry point for the application
// express application
var express = require('express');
// require the controller we make
var surveyController = require('./surveyController');
var app = express();
// set up template engine
app.set('view engine', 'ejs');
// static file serving
app.use(express.static('./public'));
// fire function from surveyController
surveyController(app);
// listen to port
app.listen(8080);
console.log('listening port 8080');
I have an HTML view of the webpage and app.js file that seem to run on the console but I get the error when I log into http://localhost:8080/showResults

Here you can use ejs as you view by below settings in your app.js
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// use res.render to load up an ejs view file
app.get('/', function(req, res) {
res.render('<folder>/index');
});

Related

.JS Not running on VS Code

const express = require("express");
const app = express();
app.get("/hello", (req, res) => {
res.send("Hello World");
});
app.listen(3000);
I run this simple code in VS code but It isn't showing in localhost 8080 on web browser
I want to know what did happen and How to solve this one ?

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.

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
}));

Displaying local images in static html served by NodeJS

I have a NodeJS app that renders index.html, but I can't get index.html to find the images in the folder it's located in.
Here are the contents of index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get ('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(80, function(){
console.log('listening on *:80');
});
It serves index.html successfully but all images I supply it are broken links.
The following html does not work
<img src="img/myimage.png">
and my file structure is
myApp - folder
index.js
index.html
img - folder
myimage.png
I've tried several variations such as
<img src="/img/myimage.png">
<img src="./img/myimage.png">
I've also tried placing the image directly in the app folder with index.html and trying
<img src="myimage.png">
But the link to the image is still broken.
const express = require("express");
const app = express();
If you have the images in a folder named "Images" and you want to point to the image in the folder as "img/myimage.png", then use this:
app.use('/img', express.static(__dirname + '/Images'));
This way you can also keep your actual images folder name private.
I was able to resolve the issue by changing
var app = require('express')();
into
var express = require('express');
var app = express();
I then added
app.use(express.static(__dirname + '/img/'));
In the declaration of static file you will use in the express app, you have to put your files (images, songs, file) into public folder. Then, your express and ejs will show your file from the public folder as a root of that file.
var express = require("express");
var app = express();
app.use(express.static('public'));
app.set("view engine", "ejs");
app.get("/", function(req, res){
res.render("main");
});
app.listen(3000, function(req, res){
console.log("Auth server started!");
});
EJS folder is right here.
<h1>Secret Page!</h1>
<img src="anna.jpg"/>
<img src="https://i.imgur.com/NcXbX08.jpg" alt="">
After all, reload your nodejs app.
Do you mean broken links in the browser ? so the browser can not open the links rendered in index.html ?
The browser will probably need full paths to the images .. it doesn't seem that your node server is sending the full paths in the index.html file it passes to the browser.. have a look on that ..

Node JS Configuration

I am trying configure my node js to run my html code.I am using bootstrap and Express Js also.When I run node js its not loading the css.Can anyone help me what could be the issue.Here is the node js code snippet.
var express = require("express");
var app = express();
var path = require("path");
app.get('/',function(req,res) {
res.sendFile(__dirname + '/home.html')
})
app.use(express.static(__dirname + '/public'))
app.listen(3000);
console.log("Running at Port 3000");
When I directly load the HTML files it loads the CSS properly but when i use node js to load it it fails.What could be the cause of the issue?
Check your directory structure is correct and that you have given the correct permission for Node.js to enter the directories and read the file.
If your directory structure looks like this:
/public
/stylesheets
home.css
home.html
server.js
And your server.js code looks like this:
var express = require("express");
var app = express();
var path = require("path");
app.get('/',function(req,res) {
res.sendFile(__dirname + '/home.html');
})
app.use(express.static(__dirname + '/public'));
app.listen('3000', function() {
console.log("Listening on port 3000");
});
When you run this:
node ./server.js
And visit this URL in your browser:
http://localhost:3000/stylesheets/home.css
You will get your home.css file returned.
In express js project to configuration database
/config
/database.js
/server.js
/.env
const http = require('http');
const app = require('express')();
require('./config/database.js');
const bodyParser = require('body-parser');
const server = http.createServer(app);
server.listen(process.env.ServerPort, '0.0.0.0', () => {
logger.info(`Express server listening on port ${process.env.ServerPort}`);
});
When you run this:
node server.js
database.js file
const My = require('jm-ez-mysql');
// Init DB Connection
const connection = My.init({
host: process.env.DBHOST,
user: process.env.DBUSER,
password: process.env.DBPASSWORD,
database: process.env.DATABASE,
dateStrings: true,
charset: 'utf8mb4',
timezone: 'utc',
multipleStatements: true,
connectTimeout: 100 * 60 * 1000,
acquireTimeout: 100 * 60 * 1000,
timeout: 100 * 60 * 1000,
});
module.exports = {
connection,
};
In express js project, as require you can place you static file.
app.use('/static', express.static('public'))
Now, you can load the files that are in the public directory from the /static path prefix.
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
https://expressjs.com/en/starter/static-files.html
check this link for how you can connect your static files with express js