Link css stylesheet with express.static problem - css

I'm just learning, so need some help with something.
When I try to load my html file on my local server it doesn't load my styles.css file.
I used the express.static on my "public" folder and modified the path of the styles.css in the html file. Some help would be great . Thanks.
The folder paths: css
C:\Newsletter-Signup\public\css\styles.css
html file that i tryed to load with applied .css on it:
C:\Newsletter-Signup\public\signup.html
!(https://imgur.com/PJO7J4H)
this is my app.js file:
const app = express();
app.use(express.static("public"));
app.get("/", function(req, res){
res.sendFile(__dirname + "/signup.html" );
});
app.listen("3000", function(){
console.log("server started on port 3000");
});
and this is my link to styles.css that doesnt load:
< link href="css/styles.css" rel="stylesheet" >

Here I am trying to present you a generic solution.So this may be helpful to fix the issue, which occurs during your code attempt.
When generating the express app project, I used the command npm install -g express-generator which recommended in Express Js official site. From that, I could easily create the folder structure for the express app.
.pug file format
By default the generated express app only allows you to render .pug file format instead of .html file. Express-generator installs pug node module via npm install pug -- save while installs other required dependencies. After installs pug dependency you are allowed render .pug files locate in the root using localhost URL.
app.js
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res, next) {
res.render('<pug file name>', { title: 'Express' });
});
Set your current directory as app root and run the command npm start from your terminal and visit the URL http://localhost:<Port Name>/
Then you can see the rendered .pug file.
Get support for .html file format
Since Express Js supported .pug file format, you need to install ejs node module to get support for the .html format.
npm install ejs --save
Then need to update app.js file content as below
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res, next) {
res.render('<html file name>', { title: 'Express' });
});
Now you will see, .html file is rendered properly.
Add a stylessheet to express app
In app.js file, a directory path is already set for static files as shown below.
app.use(express.static(path.join(__dirname, 'public')));
It means that the public folder is set as static file directory.
So, when linking a stylesheet inside head tag, a relative path for stylesheet should be stated as 'stylesheets/style.css.
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css">
</head>

Related

Using Vite.js HMR with SCSS in a WordPress theme

I'm trying to use Vite.js in a WordPress theme to process my asset files.
I've created a vite.config.js file:
import { defineConfig } from 'vite';
export default defineConfig({
root: './resources',
build: {
rollupOptions: {
input: ['./resources/test.scss'],
},
},
server: {
port: 1337,
},
});
And I'm loading the Vite.js client plus the asset from the server:
<script type="module" src="http://127.0.0.1:1337/#vite/client"></script>
<link rel="stylesheet" href="http://127.0.0.1:1337/test.css?ver=6.0.1">
But this results in a 404 error for the test.css file. When using a css/js file instead of scss, everything including HMR works fine. I'm also not getting any warning about sass needing to be installed, so I assume Vite.js skips the scss file completely for some reason.
Is it a good idea to use the rollupOptions.input option for just listing resources in the first place or is there a better way? As I'm not building a JS application, there's no entry point such as an index.html, just some js/scss files I want to process.
You need to install SASS npm add -D sass https://vitejs.dev/guide/features.html#css-pre-processors.
The input file is a JavaScript file input: 'main.js', that itself imports the SCSS files import './resources/test.scss';.
Generally, the backend integration guide would help you with the setup for a multipage app like WordPress https://vitejs.dev/guide/backend-integration.html.

Loading static files in Express

I have been trying to get my node.JS file to serve my HTML app with static CSS and JS files included too but have ran into great difficulties (the HTML file is loading, but with no styling). From my searching it seems the main recommended method is to add the Express middleware to your node.JS and then add this line:
app.use(express.static(path.join(__dirname, 'static/')));
Before I go on too much further I will show you my directory set-up:
-static
-images
-favicon
-favicon.png
-logo.png
-style
-design.css
-theme.css
-w3.css
-source
-client
-style.js
-node_modules
-...
-index.html
-root.js
-package-lock.json
-...
The 'root.js' file is my node.JS file that I am running and it serves the 'index.html' page, but all the CSS and JS files my HTML page links to come up with this sort of error...
The stylesheet http://localhost:8080/static/style/design.css was not loaded because its MIME type, "text/html", is not "text/css".
Here is one example of a line in my 'index.html' where I try to link to that CSS file...
<link rel="stylesheet" type="text/css" href="static/style/design.css">
...and here is where 'index.html' is served in my 'root.js' file...
http.createServer(function (req, res) {
fs.readFile('index.html', function (err, data) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
return res.end();
});
}).listen(8080);
I am not too sure where I am going wrong as most guides on the topic seem to imply that when I add in the magic '__dirname' line to my node.JS that everything is meant to resolve itself. When I just run my HTML page locally by opening it in Chrome or Firefox it works fine. I am hoping you might be able to explain to me where I am going wrong, thank you.

How to set Angular2 cli baseurl for a new web site?

I have an existing ASP.NET MVC web site. www.foo.com
I want to create a whole new sub system of our site using Angular2 and I want it to go under www.foo.com/NewSubSystem.
I have downloaded the Angular2 Cli from https://cli.angular.io/.
When I run from the command line
ng build -dev
The output has all the javascript script tags looking this in the index.html file
<script type="text/javascript" src="inline.bundle.js"></script>
<script type="text/javascript" src="styles.bundle.js"></script>
<script type="text/javascript" src="main.bundle.js"></script>
I need the scr="www.foo.com/NewSubSystem/inline.bundle.js"
NOTE: I have tried to update the baseURL in the tsconfig.json
"compilerOptions": {
"baseUrl": "www.foo.com/NewSubSystem"
}
but this does not seem to make any difference.
Any suggestions or pointers would be nice. Thanks
Set the index file baseref
base href="NewSubSystem/"
Then just code like its the root.
I reset the baseref to dist/ with javascript depending on the env sensed
Change your index.js files update
<base href="/<you base url>/">
if you are working with webpack:
You should also update the file config/webpack.common.js, so that you assets folder content can be hosted from your new baseurl.
...
const METADATA = {
title: 'ng2-admin - Angular 2 Admin Template',
description: 'Free Angular 2 and Bootstrap 4 Admin Template',
baseUrl: '/<you base url>/',
isDevServer: helpers.isWebpackDevServer()
};
.....

Express static won't load CSS files from root

My app is loaded from a url such as : server.com/pdf/12345. When it is looking for the static files, it tries to GET /pdf/12345/assets/css/stylesheet.css and 404s. I can't figure out how to tell it to look for /public/assets in the root. Tried a number of different express.static configurations.
my directory structure looks like this:
public
--assets
----css
views
--partials
----header.ejs
routes
--api.js
server.js
server.js looks like this (minus the requires for clarity):
app.use('/', routes);
app.set('views', './views');
app.set('view engine', 'ejs');
app.use('/public', express.static(path.join(__dirname, 'public')));
http.createServer(app).listen(port, function() {
})
My partials/header.ejs contains link to stylesheet
You should write it like this instead:
app.use(express.static(path.join(__dirname, 'public')));
If you start with app.use('/public' you are telling express to only mount the function on the path /public, in your case i guess if the url starts with server.com/public. But since that is not the case, express.static() never fires.

references to css and javascript from html don't work only on localhost

I am automatically inserting references to css and js files into html head with help of grunt-link-html plugin, but when viewing the page on http://localhost:9000/ files are not found ('Cannot GET'). The styles and scripts are referenced relatively and are showing when viewing the file by double-clicking from harddrive:
<!-- begin:css -->
<link rel="stylesheet" type="text/css" href="../deploy/css/myproject.min.css">
<!-- end:css -->
<!-- begin:js -->
<script src="../deploy/js/myproject.min.js"></script>
<!-- end:js -->
I'm new to Grunt, what am I missing? Thanks for any help
project structure:
MyProject
_build
node_modules
Gruntfile.js
package.json
deploy
css
myproject.min.css
js
myproject.min.js
src
css
myproject.css
js
myproject.js
index.html
extracts from the gruntfile:
express: {
all: {
options: {
port: 9000,
hostname: "0.0.0.0",
bases: ['C:/Users/user1/MyProject/src']
}
}
},
open: {
all: {
path: 'http://localhost:<%= express.all.options.port%>',
app: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'
}
},
link_html: {
your_target: {
jsFiles: ['../deploy/js/portfolio.min.js'],
cssFiles: ['../deploy/css/portfolio.min.css'],
targetHtml: ['../src/index.html'],
options: {
cwd: '../deploy'
}
}
}
grunt.registerTask('server', ['connect', 'express', 'open', 'watch']);
The .. at the beginning of the CSS & JS file paths are correct for Grunt if run from _build subdir, but not for the page, because index.html is at the project root directory.
I would move the Grunt stuff from _build to project's root folder and remove the .. from Gruntfile.js, too.
After a Grunt rerun it should work, then.
I am not familiar with these spesific grunt modules, but I am guessing the problem is that you define the "bases" of express.all as your src folder, and not your "myProject" folder.
So when your server wants to serve you files (like your css and js) it only looks in the /src folder, where you dont have a "../deploy/" folder.
Try changing your bases to ['C:/Users/user1/MyProject/deploy'] and your jsFiles and cssFiles, remove the "../deploy", they should now reside in the "/js" and "/css" folders.
Hope this helps :)
Just a thought or two:
1.Try using the same separator in all links, as there is a difference between "\" and "/" in some environnements (browsers vs editor vs os vs anything else).
2. (dumb question ?!) Are you sure you have read/write/execute rights on the files you are accessing ?

Resources