What's wrong with the following public directory setup? - javascript

I just built a Webpack project:
static/ // where I have the js and css file
index.html // the main file
And placed it inside the public/ folder in an Express setup:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.sendfile('public/index.html')
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
But I get these errors:
http://localhost:3000/static/app.79c874fce37c5d0a32117271eb04a7f8.css
http://localhost:3000/static/app.57fd4b2335b940c7b8d1.js 404 (Not Found)
This is the content of index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>istaging-viewer</title>
<link href=/static/app.79c874fce37c5d0a32117271eb04a7f8.css rel=stylesheet>
</head>
<body>
<div id=app>
<script src=/static/app.57fd4b2335b940c7b8d1.js></script>
</div>
</body>
</html>
(Those files exist in the /static/ directory).
How should I change the Express code so Express can find those files?
EDIT: I tried this ...
app.get('/', function (req, res) {
res.sendfile('static/index.html')
});
... but I'm still getting this error:
GET http://localhost:3000/static/app.79c874fce37c5d0a32117271eb04a7f8.css
localhost/:1 GET http://localhost:3000/static/app.57fd4b2335b940c7b8d1.js 404 (Not Found)
EDIT 2:
I tried this to serve the static files:
app.use(express.static('static'));
I still get the same errors:
GET http://localhost:3000/static/app.79c874fce37c5d0a32117271eb04a7f8.css
localhost/:1 GET http://localhost:3000/static/app.57fd4b2335b940c7b8d1.js 404 (Not Found)

So long as your app/main js file is in the same folder as your index.html, then change
app.get('/', function (req, res) {
res.sendfile('public/index.html')
});
to
app.get('/', function (req, res) {
res.sendfile('index.html')
});
Ideally, however, your file structure should look something like:
app.js
static/
index.html
js/
css/
img/
that way, you'd reference it this way
app.get('/', function (req, res) {
res.sendfile('static/index.html')
});

Related

Express static work only with filename index.html

So i have a problem with my static files. Here's my code:
const express = require ('express')
const app = express()
app.listen(4040,() => console.log("on"))
app.use(express.static(__dirname + "/public"))
Everything works. Until I change html file name in public folder
It works if it's index.html but doesn't if it's about.html or everything else.
My folders are like that:
📂Main
📂node_modules
📂public
📂assets
style.css
index.html/about.html
main.js
package-lock.json
package.json
Route must be specific, "/" for "index.html" & "/about" for "about.html". If you change from index.html to home.html, make sure your main.js (server) also follows.
const express = require("express");
const path = require("path");
const app = express();
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public/index.html"));
});
app.get("/about", (req, res) => {
res.sendFile(path.join(__dirname, "public/about.html"));
});
app.listen(4040, () => console.log("on"));
index.html (http://localhost:4040/)
<h1>HOME PAGE</h1>
about.html (http://localhost:4040/about)
<h1>ABOUT PAGE</h1>
Hey I believe I might know what's going on but wanted to clarify, you are wanting to serve multiple static files one "index.html" and another "about.html" and it's only working for the one called index.html? If this is the case this is because it defaults to reading the index.html file if it is present, the solution to this may be to rename your index.html to something else such as main.html, and see if that works properly.

Implement Posted Form from NodeJS into HTML

I recently switched from starting to learn PHP to NodeJS since I have more knowledge in JS. My question is how do I display posted form data into a HTML File?
server.js
const app = require('express')(),
bodyParser = require('body-parser'),
path = require('path');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get('/', (req, res) => res.sendFile(path.join(__dirname, 'html/index.html')));
app.post('/student', (req, res) => res.send(req.body.user.name));
app.listen(3000, (req, res) => console.log('Listening on port 3000.'));
html/index.html
<body>
<form method='post' action='post'>
<input type='text' name = 'user[name]'>
<input type='submit' value='submit'>
</form>
</body>
However in the post method, I want to send a HTML file, instead of req.body.user.name which I could obviously do like I did on the home page (/), I want to be able to include some variables into the new HTML File, maybe something looking along the lines of:
<body>
<h1><? req.body.user.name + 's page. ?></h1>
<!-- rest of code -->
</body>
I use ejs template for this purpose and it is very easy to use.
First of all, download ejs with npm install ejs -s and create a views folder inside your main directory. Inside that folder, create a normal html file but this time with an extension of .ejs.
App Directory
-views/myFile.ejs
/post.ejs
-html/index.html
-server.js
Now let's go to your server.js file. You need to use app.set('view engine', 'ejs') to run ejs. When you do res.render() you don't have specify the path because the program already looks for views/ folder in the main directory.
const app = require('express')(),
bodyParser = require('body-parser'),
path = require('path');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.set('view engine', 'ejs');
app.get('/', (req, res) => res.render('myFile.ejs', {username: 'myUser'}));
app.post('/student', function(req, res){
var username = req.body.user.name;
res.render('post.ejs', {user: username});
});
app.listen(3000, (req, res) => console.log('Listening on port 3000.'));
This is our sample myFile.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p><%=username%></p>
</body>
</html>
And this is our sample post.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p><%=user%></p>
</body>
</html>
You should use some template engine, there is tutorial on express page https://expressjs.com/en/guide/using-template-engines.html.
There is always possibility that you can write your own module for handling this.
You can also install express generator
npm install express-generator -g
then call:
express
Thanks to this you will setup express project with jade as template engine(it is default), it should allow you to progress further.

Javascript and HTML Problems

having trouble getting this to run with node
const express = require('express')
const app = express()
app.use(express.static('public')) //adds content of public folder
app.get('/', function (req, res){
res.sendFile('/views/index.html', {root: __dirname})
})
app.listen(1337, function (){
console.log('lab5-server.js listening on 1337')
})
it was running perfect yesterday and now it's not. There's also an issue with the .html portion, it wont display the image I have assigned. Quick note it that I left out most of whats written below the source code for the image, it's not necessary for this question.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1> <center> Welcome to Matt's Page </center></h1>
<center> <img src = "images/AlgorithmofSuccess.jpg"/> </center>
Does anyone see where I went wrong and why the terminal is returning "unexpected token" on the javascript portion?
You should try to use the path module to help point to your public path. I can give you an example:
const path = require("path");
const app = express();
const publicPath = path.resolve(__dirname, "./public");
// We point to our static assets
app.use(express.static(path.resolve(__dirname, "./public")));
app.get("/*", (req, res) => {
res.sendFile("index.html", { root: path.join(__dirname, "./public") });
});
// And run the server
app.listen(1337, () => {
console.log(`Server running on port ${port}`);
});
Make sure that ./public or ./dist path contains your index.html
I solved this, just had to change the folder of the lab5-server.js file i was using, thanks for the help guys

Express template not linking to scripts, css, or images

Using Express, I run the index.html file but cannot get the css, js or images to link up correctly. No images showing, css and js not linking.
<link rel="stylesheet" type="text/css" href="css/main.css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/main.js"></script>
img/logo.png
I have the following directory structure:
root
app.js
package.json
node_modules
assets
img
css
js
templates
theme1
css
fonts
img
js
index.html
about.html
services.html
news.html
contact.html
In app.js:
var express = require('express');
var app = express();
var path = require('path');
app.get('/', function(req, res) {
//res.sendFile(path.join(__dirname + '/assets/templates/theme1/index.html'));
});
app.get('/about/', function(req, res) {
res.sendFile(path.join(__dirname + '/assets/templates/theme1/about.html'));
});
app.get('/services/', function(req, res) {
res.sendFile(path.join(__dirname + '/assets/templates/theme1/services.html'));
});
app.get('/services/', function(req, res) {
res.sendFile(path.join(__dirname + '/assets/templates/theme1/news.html'));
});
app.get('/contact/', function(req, res) {
res.sendFile(path.join(__dirname + '/assets/templates/theme1/contact.html'));
});
app.listen(3000);
need better understanding of app.get and app.use as well as res.sendFile
Thanks all
So, it's not working because you're not telling Express to serve the files you want (the js and css and so on).
First you want to setup a static route using the static middleware:
app.use(express.static(__dirname + '/assets'));
At that point, everything in the 'assets' directory will be served relative to your root URL. So /img/someimage.jpg is the correct URL for it.

Serving html and javascript through structured Express app

I am currently playing with Express and attempting to solve (what I believe should be) a trivial problem.
I've got the following directory structure:
|-config
|---config.js
|---routes.js
|-server.js
|-scripts
|---controllers
|------controllers.js
|---directives
|---filters
|---services
|---templates
|---app.js
|-views
|---index.html
My server.js
var express = require('express');
var app = express();
require('./config/config.js')(app);
require('./config/routes.js')(app);
app.listen(7777);
My config.js
module.exports = function(app){
app.set('views', __dirname + '../views');
app.engine('html', require('ejs').renderFile);
}
My routes.js
module.exports = function(app, express){
app.get('/', function(reg, res){
res.render('index.html')
})
app.use(function(err, req, res, next){
console.error(err.stack);
res.send(500, 'Something broke!');
});
}
And finally my index.html
<html lang="en">
<head>
<title></title>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js'>
</script>
</head>
<body>
Hello World!!!
</body>
</html>
When I visit localhost:7000/
I get
Error: Failed to lookup view "index.html"
at Function.app.render (/Users/abe/github/leap-motion-signature-recognition/node_modules/express/lib/application.js:494:17)
at ServerResponse.res.render (/Users/abe/github/leap-motion-signature-recognition/node_modules/express/lib/response.js:756:7)
at /Users/abe/github/leap-motion-signature-recognition/config/routes.js:7:13
at callbacks (/Users/abe/github/leap-motion-signature-recognition/node_modules/express/lib/router/index.js:161:37)
at param (/Users/abe/github/leap-motion-signature-recognition/node_modules/express/lib/router/index.js:135:11)
at pass (/Users/abe/github/leap-motion-signature-recognition/node_modules/express/lib/router/index.js:142:5)
at Router._dispatch (/Users/abe/github/leap-motion-signature-recognition/node_modules/express/lib/router/index.js:170:5)
at Object.router (/Users/abe/github/leap-motion-signature-recognition/node_modules/express/lib/router/index.js:33:10)
at next (/Users/abe/github/leap-motion-signature-recognition/node_modules/express/node_modules/connect/lib/proto.js:190:15)
at Object.expressInit [as handle] (/Users/abe/github/leap-motion-signature-recognition/node_modules/express/lib/middleware.js:30:5)
Why is that? Shouldn't the __dirName set have hooked views\index.html?
Secondly, I am planning to use this server to back an Angular JS app with many javascript files. What is the Express answer to the Rails asset pipeline? How can I include entire directories painlessly, without explicit population of script tags, and, if at all possible with deploy time minification?
__dirname has no trailing slash, so you should change __dirname + '../views' to __dirname + '/../views'.
You can serve static files from a directory with the static middleware:
app.use(express.static(__dirname + '/scripts'));
express-uglify can minify your javascript files:
var expressUglify = require('express-uglify');
app.use(expressUglify.middleware({ src: __dirname + '/scripts' }));

Categories

Resources