How static files works in express js? [duplicate] - node.js

This question already has answers here:
How to server specifc static files with express.js
(11 answers)
Closed 4 years ago.
I am developing a express.js app. I am developing admin and users two routes. But in admin section I created sub directories like post, media, etc. I want to use static files like style sheet for post, media, etc.
/admin/posts/js/lib/jquery/jquery.min.js 404 92.978 ms - 19288
where this file locate in
/admin/js/lib/jquery/jquery.min.js
I put all stylesheet and javascripts file in public/admin/. and I want use this stylesheet for all sub directories like posts, media, feedback, etc
app.use(express.static(path.join(__dirname, 'public')));

You can combine static files with dynamically generated content using Express. For example you can default to serving static content, then serve dynamic content for some routes. e.g.
index.js
const express = require('express');
const app = express();
app.use(express.static('./'));
app.get('/info', function(req, res) {
res.json({ status: 'OK', timeStamp: new Date() });
});
app.listen(8080);
index.html
<!DOCTYPE html>
<html>
<head>
<title>Static Root</title>
<link rel="stylesheet" type="text/css" href="/stylesheets/test.css">
</head>
<body>
<h4 class="center">I am static content!</h4>
</body>
</html>
You'd serve this initially from one folder with index.js and index.html.
Any route other than /info will look for static files, e.g. / or /index.html will pull index.html.
You can easily add stylesheets for example, in a ./stylesheets folder
e.g.
/stylesheets/test.css
.center {
text-align: center;
color: green;
}
This is then referenced by index.html

Related

Azure app uploads from VSCode without linking static sources

I have an incredibly basic node.js server test app running on port 3000 in VSCode. The server appears to work via node on localhost or deployed to Azure, and hosts an index.html file. I have clients happy to talk to it.
/* Server.js */
const express = require('express');
const app = express();
app.use(express.json());
app.get("/", function(request, response){
response.sendFile(__dirname + "/index.html");
});
app.post("/", function(request, result){
console.log(request.body["itema"] + " " + request.body["itemb"]);
result.send("Pong!!");
});
app.listen(3000, function(){
console.log("Server started on port 3000");
});
<!-- Index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Simple App</title>
<link rel="stylesheet" href="style.css" type="text/css"/>
</head>
<body>
<h1>Test!</h1>
</body>
</html>
/*style.css*/
h1 {
color: tomato;
}
Azure Configuration Settings
The index.html links to a css file which doesn't appear to be linked when deployed. I've tried deploying the app to azurewebsites.net through VSCode, however I'm seeing the same results. Only index.html is present in the sources view. I get an error claiming it can't render the source it didn't find.
"Refused to apply style from https://<appname>.azurewebsites.net/style.css because its MIME
type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is
enabled."
If I view the advanced page (.scm.azurewebsites.net), again I can see only index.html.
Index only
But .scm.azurewebsites.net/wwwroot/ shows me the css file has been uploaded correctly.
Index and linked sources
I'm convinced it'll be a simple solution to someone and that the PATH variables will need to be set...somehow... but I've hit a brick wall and my Google-Fu has finally been exhausted.
Thanks!
Adding the following to server.js resolved the issue.
app.use(express.static("./"));
This is further explained here and is required in express to serve static files.
https://expressjs.com/en/starter/static-files.html

node server is not serving static files

I have created a nodejs application using the express framework. I have used express.static to serve my static files.
app.use(express.static(path.join(__dirname, '..', 'public')));
There is a route that server the login.html.
// serve login page
app.get('/auth/login', loginPage);
and loginPage function
loginPage(req: any, res: any) {
res.sendFile(path.join(__dirname, '..', '..', 'public', 'login.html'));
}
Now if I directly hit http://localhost:8080/login.html login page gets served with all its css and js files, so static files are getting served.
but when I hit http://localhost:8080/auth/login only login.html is served and the other css/js files showing 404 status.
If I check the request on browser network window request is for http://localhost:8080/auth/css/bootstrap.min.css, this is appending auth prefix.
but when I change URL mapping to /auth from /auth/login then it works fine.
How can I solve this?
I was linking other js and CSS files without using / in href attribute. Like this
<link href="css/bootstrap.min.css" rel="stylesheet">
So I changed all the href by appending the /
<link href="/css/bootstrap.min.css" rel="stylesheet">
and now this is working. Thanks to #Patric

How to add static file from `node_modules` after declare the `public` as static in express?

In my express app, I am keeping the below config:
var express = require("express");
var path = require("path");
var jsonServer = require("json-server");
var app = express( );
app.use(express.static('public'));
app.get("/", function( req, res ) {
res.sendFile( express.static( path.join(__dirname, "/public/index.html" ) ) );
});
app.use('/api', jsonServer.router('./db.json'));
app.listen( 3000 );
All this is works fine. the problem is, I am not able to add the jquery from node_modules. here is my HTML :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Promise Defined</title>
<script src="node_modules/jquery/dist/jquery.js" type="text/javascript"></script> //not working sibling folder of public
<link rel="stylesheet" href="styles/app.css"> //works fine. inside public folder
</head>
<body>
<h1>New Title</h1>
</body>
</html>
What is the correct way to fix this? or how to handle this kind of scenario?
Thanks in advance.
node.js does not serve any files by default (unlike some other web servers). So, if you want node_modules/jquery/dist/jquery.js to work, then you have to either make sure that your express.static() line of code will include that file or you have to define a route specifically for that file. Also, it is sometimes dangerous to use a relative path with no leading / because that makes it relative to the path of your page which is generally not necessary and can make things difficult if you want to serve the same file in lots of different pages on your site.
For example, you could do this in the web page:
<script src="/jquery.js" type="text/javascript"></script>
And, this:
app.get("/jquery.js", function(req, res) {
res.sendFile(path.join(__dirname, "node_modules/jquery/dist/jquery.js"));
});
Personally, I would probably move jquery.js to a public/scripts directory on my server so I'm not serving anything out of the node_modules directory, so all my publicly served files are centralized in one place so it's entirely clear what can be served to a client and what cannot and so I could design one or two express.static() statements to serve all my public files.

Provide an HTML page with JS with node.js and express

I am trying to serve an html page with a linked js script using node.js and express.
This is the server that provide the page:
var express = require("express");
var app2 = express();
app2.get('/', function(req, res) {
res.sendfile('./index.html');
});
app2.listen(process.env.VCAP_APP_PORT || 3000);
and this is the page:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
</head>
<body>
<h1>Demo</h1>
<script src="/js/socket.io.js"></script>
<script src="/js/codice.js"></script>
</body>
As you can see I have two js scripts in my js folder but they are not loaded when I launch the page. What can I do?
What you would normally do is place any public resources (JavaScript files, CSS files, images etc) in a directory (Express names it public by default) and then use the express.static middleware in your app.configure call:
app.configure(function () {
// Various other middleware functions...
app.use(express.static(path.join(__dirname, "public")));
});
This effectively runs a static file server which will return any file inside the public directory. Currently, your browser is making a request for your JS files, but the Express server doesn't know what to do with them. They will eventually time out.
If you generate the initial state of your app with the global express executable (available if you installed Express via npm globally), it will set most of this up for you.

node.js - can't load my files with express3

I am using express3 and when I'm trying to load my html/javascript/css files it loads the html without the css.
I'm using this code to load the files -
express.get('/', function (req, res) {
res.sendfile("index.html");
res.sendfile("style.css");
res.sendfile("script.js");
});
So what can I do?
First, link the css and javascript to the page via tags in the header of your HTML
<link rel='stylesheet' href='/path/to/style.css' />
<script src='/path/to/javascript.js'></script>
Be sure that you're using the static middleware in your app.use() section, this will tell Express where to find your static files.
app.use(express.static(__dirname + '/public'));
Now, your Express app should serve your static css and js files.
You link to css and javascript from the html page...
Try looking at the static files example app in the express github repo: https://github.com/visionmedia/express/tree/master/examples/static-files
Basically you make another http request for static files (.js, .css)

Resources