I'm trying to send my 'index.html' file as a response to my local server and within that index.html, there is a link to an external CSS file.
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", function(req,res){
res.sendFile(__dirname+"/index.html");
});
and I've included the link in HTML head element like below:
<link href="styles.css" rel="stylesheet" >
Now the problem is that the 'styles.css' file is not loading up on the page. And on the Network section of the Chrome developer tools, it is showing status: canceled in front of the 'styles.css'.
Here is the screenshot of the canceled status showing for styles.css
Why is this happening and what is the solution to it? I've tried other people's solution of deleting the cache, but it doesn't work.
EDIT: Here, I have the exact same problem , and I've tried their solutions too, but it won't work
EDIT2: As I tried #wilkoklak's solution , It's still the same error
I just added the whole thing from the Bootstrap examples so don't really think that would be a problem
You have to serve the css file as well!
You can do this by using express.static
Create a folder named css and move your styles.css there
Your project structure would look similiar to this
project/
css/
styles.css
server.js
index.js
Then add this middleware:
app.use(express.static('css'))
This middleware will look for any match with files inside css folder, and send them in response.
When you GET / (when you open your webpage), the browser also sends GET /styles.css to your server. There was no route handler for /styles.css in your app. express.static does that for you
The problem of css not being loaded can be solved by using express.static and a dedicated static folder (Example: www) for static files.
Here is the working example using express.static:
Step 1: Put static files (index.html, styles.css in a static folder named www)
Folder structure:
/nodejs-web-demo
--> server.js
/www
--> index.html
--> styles.css
Step 2: Create the index.html and styls.css files in www (static) folder
File name: www/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/styles.css">
<title>Expressjs website</title>
</head>
<body>
<p class="my-style">Hello! How are you doing?</p>
</body>
</html>
File name: www/styles.css
.my-style{
color: blue;
}
Step 3: Use express.static to serve files from static folder
const http = require('http')
const express = require('express')
const path = require('path')
const app = express()
app.use(express.static("www"))
app.use('/', function(req,res) {
res.sendFile(path.join(__dirname + '/www/index.html'))
})
const server = http.createServer(app)
const port = 3000
server.listen(port)
console.log('Web server started on port # ' + port)
Output:
> node server.js
Web server started on port # 3000
Related
I am fairly new to Node JS and I am trying to create a server that when a user navigates to http://localhost:8000/, they are routed to index.html. In that index.html file there will be a button that they can click to obtain JSON data. This JSON data is downloaded onto my own machine with the purpose of being hosted on a Node JS server. There is 6 JSON files.
My question is, can I host the JSON and the index.html on the same server without using a framework like Express? I have a solution in express, but I would like to do so without if possible.
index.html -> press button -> get JSON from server (same server?)
--- EDIT ---
It is for a university module and was given the outlined instructions. Explicitly Node.
Setup environment
mkdir server
cd server
npm init
npm install express
touch server.js index.html
mkdir public
Server.js
const express = require('express');
const app = express();
const path = require('path');
app.use('/public', express.static('public'));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(80, () => console.log("Running on: http://localhost"));
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Download JSON</title>
</head>
<body>
<h1>Download</h1>
Sample JSON
</body>
</html>
Put your JSON in the public folder structure and link to it regularly like in the HTML example above.
you can check on express js about static file.
for example:
app.use('/static', express.static('public'));
more information in:
https://expressjs.com/pt-br/starter/static-files.html
I was overcomplicating the question received. I was told to just use http and fs libraries and access JSON like, localhost/8080/path/to/json.
Apologies for the question.
I have a small react app that I've built using webpack, it compiled to /dist/bundle.js. I then have an express server to serve an HTML file the references my bundle.js. This way when I connect to my express server it will contain my React app. The HTML file being served by express is the following:
<!DOCTYPE html>
<html>
<head>
<title>The Minimal React Webpack Babel Setup</title>
</head>
<body>
<div id="app"></div>
<script src="./dist/bundle.js"></script>
</body>
</html>
But when running locally and opening this in a browser nothing shows. When inspecting the source I can see the HTML file is there, but nothing is showing on the page.
My server.js is the following:
var express = require('express');
var app = express();
var path = require('path');
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
Why can't I see my React app? Thanks for any help!
When inspecting the page I see the following (can't really copy & paste so added a screenshot):
You need to include access to the static assets on your server.
app.use(express.static('dist'));// put the correct folder here
https://expressjs.com/en/starter/static-files.html
Have an angular application:
This is part of my index.html page:
<!DOCTYPE html>
<html lang="en" ng-app="ReApp">
<head>
<meta charset="UTF-8">
<title>REApp</title>
<link rel="stylesheet" href="./lib/bootstrap/dist/css/bootstrap.min.css">
<script src="./lib/angular/angular.min.js"></script>
</head>
<body></body>
</html>
This is part of my server.js(start point):
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.use('/api', api);
app.get('*', function(req, res){
res.sendFile(__dirname + '/public/app/views/index.html');
});
Problem is: when i have one route (localhost:3000/first) everything working. When i have route something like that: localhost:3000/first/second, i have an error "Resource interpreted as Stylesheet but transferred with MIME type text/html". In the terminal i have get request - first/second/lib/angular/angular.min.js. Of course i don't have that link. May who knows how to set a start page for this links in undex.html?
To fix this issue all you have to do is place the <base href="/"> element just below the <title> element in the head section of index.html page.
In my case, I was using packages installed by bower (the same should work for npm or yarn or any other package manager installed packages as well).
Add this middleware somewhere in your express code, before any other route declarations.
app.use('/assets', express.static(path.join(__dirname + '/bower_components')));
The first argument /assets is just a virtual path that doesn't have to exist in your project, and the second one is telling express to serve static assets from the bower_components folder.
Next, in your markup, have your stylesheet inclusions like the following:
<link rel="stylesheet" href="/assets/bulma/css/bulma.min.css">
I want to load local jquery file in my node js chat application.I have searched a lot but i cant find a proper solution.
<!doctype html>
<html>
<head>
<title>Socketio</title>
</head>
<body>
<!--This wont work -->
<script src="/socket.io/jquery.min.js"></script>
<!--This will work -->
<script src="/socket.io/socket.io.js"></script>
</body>
</html>
I just copy jquery.js file to socket.io folder.The socket.io.js file loads properly but jquery file didnt.Please help me
Here is my index.js file
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
server.listen(3000, function(){
console.log('listening on *:3000');
});
Finally I found the answer.I simply load the jquery file from localhost by this way http://localhost/assets/jquery.min.js.
app.use('/assets', express.static('assets'))
Put your jquery.min.js file in relative "/assets/jquery.min.js" path, then access as http://localhost/assets/jquery.min.js
"localhost" could be your ip address also.
Personally, I need this because I need a completely self contained demo to run independant of an available internet connection. Murphy's law is alive and well come conference time.
You might want allow Express framework to render HTML and pass in the static jQuery files. That's how I would do it.
This page explains how you can restructure your app to serve jquery files through the node routes instead of HTML code.
app.get('/jquery', function(res, req){
res.sendFile(__dirname + '/jquery.js');
});
This is what worked for me. (inside app.js)
const express = require('express');//path to express module
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
My file structure looked like this:
server.js
app.js
> public
index.html
> assets
> js
jquery.min
Then import jquery from index.html like normal:
<script src="assets/js/jquery-3.3.1.min.js"></script>
One workaround is to use the online source file link.
Try loading the jquery using the following,
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
That works fine at my end.
I'm trying to serve static files from Node.js the only problem I'm having, is if I keep going into sub paths, like so:
localhost:3000/foo/bar/baz/quux
Then I have to step up the same amount of times, like this:
../../../../public/javascripts/whatever.js
As you can see that gets really annoying, is there a way to make Express v3 just know so that I can just do /public/javascripts/whatever.js instead of having to step up? Thanks in advance
This is my current static middleware for Express`
app.use("/public", express.static(__dirname + '/public'));
If you reference your static files from the root (i.e. src='/some/path/to/file.js'), the url should not matter.
Example Website using Static Routing
Directory Structure
/public
/css/style.css
/js/site.js
/vendor/thoughtbrain/js/awesome-town.js
/views/view.html
/app.js
view.html
<!DOCTYPE html>
<html>
<head>
<!-- These files are served statically from the '/public' directory... -->
<link href="/css/style.css" rel="stylesheet" >
<script src="/js/site.js"></script>
<!-- ... while this is "mounted" in virtual '/public' -->
<script src="/public/js/awesome-town.js"></script>
</head>
<body><p>Express</p></body>
</html>
app.js
var express = require('express'),
http = require('http'),
path = require('path'),
app = express();
// Remember: The order of the middleware matters!
// Everything in public will be accessible from '/'
app.use(express.static(path.join(__dirname, 'public')));
// Everything in 'vendor/thoughtbrain' will be "mounted" in '/public'
app.use('/public', express.static(path.join(__dirname, 'vendor/thoughtbrain')));
app.use(express.static(path.join(__dirname, 'views')));
app.all('*', function(req, res){
res.sendfile('views/view.html')
});
http.createServer(app).listen(3000);
With this application running,
http://localhost:3000
and
http://localhost:3000/foo/bar/baz/quux
both serve view.html and all referenced assets resolve.
Express Framework has a section on the use of static middleware here.
With that static() configuration, Express is already at least capable of finding /public/javascripts/whatever.js.
Though, it does depend on whether your public folder is in the same directory as your script (due to the use of __dirname when specifying the path).
If it is, the URL prefix /public should map to the file-system prefix of ./public (with . being __dirname) so that:
A URL of `/public/javascripts/whatever.js`
Maps to `./public/javascripts/whatever.js`