Cannot load stylesheets node - node.js

I have created basic node/express server
var express = require('express');
var app = express();
var path = require('path')
var port = 8080;
app.use("/styles", express.static('../public/styles'));
app.get('/' , function( req , res ){
console.log(__dirname)
res.sendFile(path.join(__dirname,'../public/html/index.html'))
})
app.listen(port)
structure of project is simple
app
public
html
index.html
styles
javascripts
routes
server.js
html file looks very simple
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../styles/index.css">
<title> Hello world!</title>
</head>
<body>
</body>
</html>
yet it still complains
GET http://localhost:8080/index.css 404 (Not Found)
Yet my paths should be correct , i looked up this problem and every answer is about using
app.use("/styles", express.static('../public/styles'));
so browser know how to redirect when looking for a stylesheets. Which does not work for me.
Could anybody help with this common problem?
Thanks!

Not clear what your project structure is. It's more common to have app.js in your project directory contain the basic express server and if you have complicated routing, do that in routes/server.js
So you could change your project structure:
app.js (main file)
public
index.html
styles
index.css
javascripts
routes
server.js --not needed?
If that's the case, change app.js to:
var express = require('express');
var app = express();
var port = 8080;
//use static folder public to serve everything up
app.use(express.static('./public/'));
app.listen(port)
In index.html, to include index.css:
<link rel="stylesheet" href="/styles/index.css" >

Related

How do I get HTML-linked JS files to use Require?

I am an express newbie, and I am trying to get a static HTML page to read details from a file in Express.
Initially I had a static HTML page where users could register where they were based on a particular day (as we are now rather flexible with working arrangements). However, it became apparent that I needed to store the current situation somewhere each time someone updated their details (and retrieve it when someone else signs on), so I did some investigating and came up with Node and Express.
I have an HTML file in the public directory, and it links to a JS file where I want to do a "fs" read.
app.js
app.use(express.static(path.join(__dirname, 'public')));
var steveRouter = require('./routes/steve');
app.use('/steve', steveRouter);
routes/steve.js
var express = require('express');
var path = require('path');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.sendFile(path.resolve(__dirname, '../public', 'steve.html'))
});
module.exports = router;
public/steve.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello World : title</title>
<script src="steve.js"></script>
</head>
<body onLoad="loadUp()">
<h3>small-ish heading</h3>
</body>
</html>
public/steveHtml.js
const fs = require('fs');
function loadUp() {
alert("Ciao");
let rawdata = fs.readFileSync('student.json');
let student = JSON.parse(rawdata);
console.log(student);
alert(student.name);
}
The server starts ok, but the browser shows the message "Uncaught ReferenceError: require is not defined at steveHtml.js:1"
This is probably the wrong way of doing it, but I would love to know :
how do I get the "called" JS file to recognise the require command?
is there a better/simpler/easier way of accomplishing what I want?

Can i connect an already created angular project with nodejs(express)

I already created an angular website in which i have done routing and connected to firestore. but now i want a middleware connection because i want the values scanned by RFID scanner(Rasberry PI)to get stored in firestore.
So can i connect this angular project with node as per now or do i need to rebuild my app?
I already tried to connect using node js but when i am running the server the screen is blank and only title is displayed
------IN SERVER.js---------
const express = require('express');
const path = require('path');
const http = require('http');
// const bodyParser = require('body-parser');
// const morgan = require('morgan');
const proxy = require('express-http-proxy');
// const cors = require('cors');
const request = require('request');
const app = express();
// app.use(cors());
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
// Catch all other routes and return the index file
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '3001';
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, () => console.log(`API running on ${port}`));
-------IN DIST/index.html --------
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Miracle Bus Track</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>
<body>
<app-root></app-root>
</body>
</html>
The answer is 'yes', as client side JS UIs are usually decoupled from backend and can be hosted wherever.
However, your specific issue sounds like a code/build issue that Stackoverflow won't be a good place to sort out. One thing I see is you don't reference a tag anywhere for the angular javascript so you should start there.
Looking at the scenario you mentioned, I would like to suggest you some different approach to handle this.
I would suggest you to use Google Cloud function https://cloud.google.com/functions/ instead of creating your own nodejs server.
Cloud functions are serverless functions run on nodejs server.
I am suggest this because you are already using Firestore.
I am suggesting so e architectural changes in your project.
Google also provide IOT module. That may help you more to cuumunicate to your Raspberry Pi.

Get URL value in static page in Express.js

I am beginner to node and express. In my current application the page is displaying using this code :
var app = express();
app.use(serveStatic('static', {'index': ['index.html']}));
and in static folder, there are there files:
css, index and a js file
Listening to 3000 port it is working normally.
But what if I want to access URL like this :
localhost:3000/name=someName
I want to use this name parameter in my js file which is available in static folder.
or suggest any other routing method to do that?
If you want to get the query parameters in your .js file it can be done. So the code would look like this:
Server (index.js)
"use strict";
var express = require("express");
var serveStatic = require('serve-static');
var app = express();
app.use(serveStatic('static', {'index': ['index.html']}));
app.listen(3000);
console.log("Static express server started");
HTML (/static/index.html)
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body onLoad="readParameters()">
<div>
<h3 id="1" >Loading..</h3>
</div>
</body>
</html>
Client side JavaScript (/static/test.js)
var readParameters = function()
{
console.log('Getting parameters..');
let params = (new URL(location)).searchParams;
console.log('Query parameters: ', params.toString());
var html = 'Query parameters: ';
for (let p of params) {
html += "<br/>" + p.toString();
}
$("#1").html(html);
}
Then you can test by entering:
http://localhost:3000/?test=value
Into your browser.
You should see:
Query parameters: test=value
on the index page.
The code tree should look like this:
root
¦ index.js
¦
+---static
index.html
test.js
3 Files:
/index.js (Node server side code)
/static/index.html (HTML)
/static/test.js (Test JavaScript file)
You can defined route like below,
router.get('/name=:id', function(req, res, next) {res.render('index', { title: req.params.id});});
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. This captured values we can access with 'req.params' object. for reference https://expressjs.com/en/guide/routing.html

Can't get stylesheet to work with ejs for node.js

I'm trying to make a simple server with node, express and ejs for the template. I've gotten the server to point to the page, load it, and am even able to generate other bits of code with the include statement. However for some reason the style sheet will not load.
app.js
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
fs = require('fs');
var PORT = 8080;
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.render('board.ejs', {
title: "anything I want",
taco: "hello world",
something: "foo bar",
layout: false
});
});
app.listen(PORT);
console.log("Server working");
The ejs file is in a directory views/board.ejs
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='../styles/style.css' />
</head>
<body >
<h1> <%= taco %> </h1>
<p> <%= something %> </p>
</body>
</html>
and style.css is in a styles/style.css directory relative to app.js
p {
color:red;
}
I've tried every path that I can conceive of for the href of the link including relative to where my localhost points relative to app.js relative to board.ejs and even just style.css but none seem to work. Any suggestions are greatly appreciated.
Declare a static directory:
app.use(express.static(__dirname + '/public'));
<link rel='stylesheet' href='/style.css' />
in app.js:
you must first declare static directory
app.use("/styles",express.static(__dirname + "/styles"));
in ejs file :
<link rel='stylesheet' href='/styles/style.css' />
Recently I was working with this same thing and my CSS was not working. Finally, I get the trick. My static path was like below,
const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const staticDirectory = express.static(publicDirectoryPath);
app.use(staticDirectory);
and my folder structure was like
The trick is that express access only defined static path, in my case CSS was outside of public so it was not working and suddenly I move CSS folder inside my public folder and that's it. Works beautifully.
Above example was for only one static path. For multiple static path you can use the code in the below
const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const cssDirectoryPath = path.join(__dirname, '../src/css');
const staticDirectory = express.static(publicDirectoryPath);
const cssDirectory = express.static(cssDirectoryPath);
app.use(staticDirectory);
app.use('/css/',cssDirectory);
And my generic HTML file is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
<link rel="stylesheet" href="../css/styles.css">
</head>
<body>
<h1>this is index page</h1>
</body>
</html>
To set the entry point for your application dependancies like css, img etc add below line into your server.js (or which ever being used).
app.use(express.static(__dirname + '/'))
This tells to get css files from current directory where server.js is present. Accordingly you can define relative path of css in html file.
With Express 4, you can easily set this up by using the following within your app.js file.
app.use('/static', express.static(path.join(__dirname,'pub')));
Place this early in your file, after you created your require constants, and declared your express app.
Its declaring a static directory, with the help of the path object, allowing you to have a place where all of your front-end resources are available. It's also giving it a virtual directory name (/static) that can be used on the front of the site, instead of the physical name you see within your project (/pub).
In your template you can do something like this in your head
<link rel="stylesheet" href="/static/css_bundle.css"/>

Can not get CSS file

My directory set up is like this :
app.js
vews
home.html
css
style.css
My home file is like this :
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
</body>
</html>
My app is like this :
var io = require('socket.io'),
url = require('url'),
sys = require('sys'),
express = require('express'),
http=require('http');
var app = express();
var server = http.createServer(app);
var socket = io.listen(server);
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.get('/', function(req, res){
res.render('home');
});
app.listen(4000);
sys.puts('server running ' + 'now ' + Date.now());
The problem is when i run the app, css file can not be loaded.
Since .css files are static files you have to serve them to the clients. However, you do not serve static files as a express middleware. Add the following middleware to your express app and move the css folder under the public directory (you should create a public directory)
app.use(express.static(path.join(__dirname, 'public')));
So your final directory structure should look like this
app.js
views
home.html
public
css
style.css
And do not forget to require path module
var path = require('path')
In one of my apps, I have these relevant files in this file structure:
/
index.js
/public
/stylesheets
main.css
/views
/partials
header.ejs
The index.js includes app.use(express.static(path.join(__dirname, '/public')));
Note the /public.
The header.ejs partial includes <link rel='stylesheet' type='text/css' href='/stylesheets/main.css' />
Note the lack of public, it’s implied by the middleware.
In your example, your current directory for static files doesn’t match where you are keeping static files.
Try this:
<link rel="stylesheet" type="text/css" href="/css/style.css" />
This might solve the problem.

Resources