Nodejs Express not loading script files - html

I am trying to run a angular app thru node-express.
1 File Structure
AngularNode
public
/core.js
/index.html
project.json
server.js
2 server.js
var express = require('express');
var app = express();
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
// listen (start app with node server.js) ======================================
app.listen(8000);
console.log("App listening on port 8000");
3 index.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="./core.js"></script>
........
4 core.js
angular.module('MySystem',[])
.controller('AppController',['$scope',function($scope){
$scope.Name ="Testing Text";
}]);
When I tried to run this app using node server.js this, index.html file is getting loaded properly, however this is not detecting or loading core.js file. and I am getting following errors
Uncaught SyntaxError: Unexpected token < core.js:1
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.5/$injector/modulerr?p0=MySystem&p1=Error%3…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.4.5%2Fangular.min.js%3A19%3A381) angular.js:38
Now, when I open index.html file directly from explorer, this is working OR when same code I move from core.js to inline html, under <head> with <script> block it is working.
I am not sure, why core.js not detecting or loading when I run thru node.

Got the Solution with few modifications:
1 Added line in server.js
app.use(express.static(__dirname + '/public')); after line
var app = express();
2 Case correction(Capital 'f') for function from res.sendfile('./public/index.html'); to res.sendFile('./public/index.html');
Now I can see core.js is detected and working fine.

The app.get('*', function(req, res) { is a catch all rule for all get request and will also match the ./core.js request. So for the ./core.js your express app will also send the html file.
You should use express.static instead:
var express = require('express');
var app = express();
app.use(express.static('./public'));

Related

Trying to load my html file using nodejs to create login page

I am trying to use node.js to run a html file. I already have a login.html and styles.css for for the login page but now I don't know how to use the node js file to run my login.html page. I follow this youtube tutorial to make the a login authentication. It seems to have everything needed but now I dont know how to use it in my login.html file.
I need help modifying this so that I can run my login.html file.
index.js file
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const postRoute = require('./routes/posts');
//Import Routes
const authRoute = require('./routes/auth');
dotenv.config();
//Connect to DB
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => console.log('Connected to DB')
);
//Middleware
app.use(express.json());
//Routes Middlewares
app.use('/api/user', authRoute);
app.use('/api/posts', postRoute);
// start listening
app.listen(3000, () => console.log('Server up and running port:3000'));
I am new to node.js and am completely lost on how to solve this problem.
you can solve it in two ways, first you can install view engine like ejs and use res.render (if you want more about it i can explain)
Second you can response with the HTML file like this: (works only with express and you have express)
app.get('/yourRotue', function(req, res, next){
res.sendFile(__dirname + '/yourPath/htmlFile.html');
});
How to use EJS (basic):
First please install EJS with npm install ejs install body parser npm install body-parser
now you need to create two folders on the root folder, public and views.
inside views you can create a folder auth and put your EJS files there.
then on your app.js (or index.js, the main file) add view engine middleware:
(*notice that you dont need to require ejs, also notice you dont need to install path its built in with node)
//import body parser on top (to parse json/urlencoded/text..
const bodyParser = require('body-parser');
//import path so you can use it for the public folder
const path = require('path');
//this line makes public folder public so you can store js/css/image...
app.use(express.static(path.join(__dirname, 'public')));
//use the body parser as middleware
app.use(bodyParser.json({ limit: '200mb' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.text({ limit: '200mb' }));
//this line tells node js to use ejs
app.set('view engine', 'ejs');
//this line make sure that the views folder is the folder with the ejs files
app.set('views', 'views');
//now your route will look like this:
app.get(/routeName, (req,res,next) => {
let example
//you return response with render, to render the file you want.
// you dont write the views folder name, only the file name without .ejs
// elso you can run functions here and later send the response to the front end
function(){
example = 1 + 1 * 5
}
// *very often the function above is to find something in the db
return res.render('auth/ejsFileName', {
pageTitle: 'some page title for the example',
exampleKey: example
})
})
I can suggest you to use mvc (models, views, controllers) structor, if you want to know more about it you can open new question or to search about it.
EJS:
put your css and js in public folder, you can create js folder and css folder inside the public folder and then put the css in js in their folder.
*notice you dont need to write ./public in the route.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/css/someCssFile.css">
<!-- here is the title that comes from the back end -->
<title><%= pageTitle %></title>
</head>
<main>
<h1>Here you can see the example with the function<%= exampleKey %></h1>
</main>
<script src="/js/someJsFile.js"></script>
</body>
</html>
the file look like html but it has .ejs
there is many things you can do with ejs like to loop through values.. i would suggest to learn a bit more.
this is the basic it should work.
For the post request i need to know if you are posting a form as urlEncoded or json. so i can show you how it should look like.
You can try to use some template engines like Handlebars. https://youtu.be/1srD3Mdvf50 You can try to follow this tutorial in order to load some html from the server side. Then you can use different selectors in order to interact with DOM elementa

Failed to load resource: the server responded with a status of 404 (Not Found) issue in Nodejs app

I need help. I looked up the solutions here but still couldn't find it. So I'm practicing something in Goorm ide and I have come to a dead-end. I am trying to link main.js(which is in js folder) file by putting the script in the footer. But I'm getting an error which says
Failed to load resource: the server responded with a status of 404 (Not Found)
I also uploaded some png files in lib folder and I'm getting the same error after trying to access those in an ejs template.
Root folder consists of js, lib and views folder and some others which are not relevant.
To link the main.js in footer.ejs(which is in partials folder inside views), I used
<script type="text/javascript" src="../../js/main.js"></script>.
The png images which are uploaded in lib/images folder, I tried to access those from an ejs template in views so I used
<img src="../lib/images/image1.png">.
I am getting that error in both the cases. It would be highly appreciated if someone could help. This is how my root folder looks like -
EDITED:
This is the app.js code:
require('dotenv').config();
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var indexRoute = require("./routes/index");
var flash = require("connect-flash-plus");
var session = require('express-session');
// APP CONFIG
app.use(express.static(__dirname + "/public"));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended:true}));
app.set('json spaces', 2);
app.use(session({
secret: 'boom',
cookie: { maxAge: 60000 },
saveUninitialized: true,
resave: true
}));
app.use(flash());
app.use(function(req, res, next) {
res.locals.error = req.flash("error");
next();
});
// routes
app.use(indexRoute);
app.listen(3000, function(){
console.log("Server has started");
})
Your Express configuration specifies that all of your static files will be accessed from the public directory:
app.use(express.static(__dirname + "/public"));
This means that any files you want to access in your web browser must be within this directory (or a subdirectory of it).
For instance, if you want to access main.js, and it's location in public/main.js, you would access it on the frontend like this:
<script type="text/javascript" src="/main.js"></script>
Note that on the frontend, you must not include the public/ prefix.

Setting up URL base for JSON with expressjs

I am completely new to node ExpressJS and am required to rewrite a rule for my server data source (jason format).
./
../public/
/public/css
/public/js
/public/index.html
../datasource/
/datasource/carmodel.json
The default static directories are set in:
app.use(express.static(__dirname + '/../public'));
The above work and everything runs under the 3000 port fine locally.
I need to rewrite the URL for my json file (datasource/carmodel.json) by replacing datasource with car/models/. However my application is unable to find the /datasource/carmodel.json file. I have attempted to recreate this via the following:
app.use('car/models/', require('./../datasource/'));
But I still cannot find the json source URL. It does not matter if I type: http://localhost:3000/car/models/carmodel.json or http://localhost:3000/datasource/carmodel.json for that matter. Is there something I am missing?
------------------
EDITED
------------------
Please see my project structure:
./
node_modules/
public/
css/
custom.css
js/
app.js (angular)
index.html
datasource/
carmodel.json
index.js (express file)
package.json
README
Currently my static folder is running of localhost:3000/. Contents of datasource/index.js:
var express = require('express');
var app = express();
app.use(express.static('public'));
//json
app.get('/car/models/:filename', function(req, res){
var filename = req.params.filename;
var fileDir = 'server/' + filename;
res.download(fileDir);
})
app.listen(3000, function(){
console.log('App started on port 3000!');
});
check something like this:
app.get('/car/models/:filename', function(req, res){
var filename = req.params.filename;
var fileDir = __dirname + '/datasource/' + filename;
res.download(fileDir);
})
then this http://localhost:3000/car/models/carmodel.json should work. I dont test it, youst write from head, therefore there may be some typos.
My solution is not safe. You shoud validate 'filename' before production use (all data from user must be validated).

node.js code to open a page in browser with localhost URL

I have written a simple server using node.js. At the moment the server responds by writing "hello world" to the browser.
The server.js file looks like this:
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8080);
I use this URL in the browser to trigger the "hello world" response:
http://localhost:8080/
I want to be able to open a basic html page when I pass a URL like this:
http://localhost:8080/test.html
I have looked through many tutorials and some stackoverflow posts but there was not much out there on this specific task. Does anyone know how to achieve this with a simple modification to the server.js file?
If you wish to open .html file through nodejs with the help of "http://localhost:8080/test.html" such url, you need to convert .html page to .jade format.Use rendering engine with the help of expressjs framework.Express rendering engine will help you to render .jade file on nodejs server.
It is better to use a front end javascript frameworks such as Angular, React or Vue to route to different pages. Though, if you want to do it in Node, you could do something like this using express:
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.sendFile('views/index.html', { root: __dirname })
});
app.get('/test', function(req, res) {
res.sendFile('views/test.html', { root: __dirname })
});
app.listen(8080);
This is an ok solution for static pages. Express is very useful for writing REST API's.

Express routing returns undefined randomly

I am trying to learn Express with NodeJS and would like to render my views with plain HTML. I hacked together a webserver based on the Express API documentation and several Stack questions, particularly the answer by Andrew Homeyer in this question which states
You can have jade include a plain HTML page:
in views/index.jade
include plain.html in views/plain.html
... and app.js can still just render jade:
res.render(index)
My directory structure looks like this
Project
*web.js
Public
img
js
lib
gallerific
*jquery.opacityrollover.js
*jquery.gallerific.js
angular
theme
views
partials
*index.html
*index.jade
and my server looks like this.
var express = require('express'),
jade = require('jade');
var app = module.exports = express();
app.configure(function(){
app.set('views', __dirname + '/public/views');
app.use("/public/lib", express.static(__dirname + "/public/lib"));
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.set('view engine', 'jade')
app.use(express.bodyParser());
});
app.get('/', function(req, res) {
res.render('index');
});
app.get('/partials/:name', function(req, res){
var name = req.params.name;
res.render('/public/partials/' + name);
});
app.get('/public/data/:name', function(req, res){
var name = req.params.name;
res.json('/public/data/' + name)
});
app.listen(3000, function(){
console.log("Express app listening on port %d in %s mode", this.address().port, app.settings.env);
});
What I am seeing is that certain files fail to load from directories in which everything else loads just fine. For example, my Gallery page fails to load the jquery.gallerific.js javascript file from my lib/gallerific directory while it does load the jquery.opacityrollover.js. I have poked around with Chrome Developer Tools and see the following
I had this site working with the Angular Bootstrap webserver so it doesn't seem to be a javascript error with the client side code. Does anyone know what I might doing that would cause this problem?
The source is available at https://github.com/jamesamuir/express-simple-html.git
I figured it out. It turns out I had to resolve paths that I had forgotten about so that Express could render them correctly. It wasn't that the Gallerific javascript library didn't load, it was throwing an error on the image source of undefined for my gallery images (I am pulling them from a JSON file).
Once I put the appropriate paths in for the images and the data file, everything started working again. Thanks to everyone who provided a suggestion for me. It really helped me to work through the problem.