Here is my current folder structure
css
app.css
js
app.js
node-modules
index.html
node-server.js
package.json
The node-server is hosting index.html, but I can't figure out how to get the app.js and app.css files to get loaded.
index.html loads them with:
<script src="js/app.js"></script>
<link rel="stylesheet" type="text/css" href="css/app.css"/>
Here is the error message:
Failed to load resource: the server responded with a status of 404 (Not Found)
2http://localhost:3000/css/app.css Failed to load resource: the server
responded with a status of 404 (Not Found)
I know i need to require or load module or something, just can't figure out what.
Thanks
Reason
Node.Js does not server static content on it's own, routes has to defined for serving static content via Node.
Solution(Manual):
var express = require('express'),
path = require('path'),
app = express();
app.get('/index.html',function(req,res){
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/css/app.css',function(req,res){
res.sendFile(path.join(__dirname + '/css/app.css'));
});
app.get('/js/app.js',function(req,res){
res.sendFile(path.join(__dirname + '/js/app.js'));
});
app.get('/', function(req, res) {
res.redirect('index.html');
});
app.listen(8080);
Better Solution:
Directory Structure:
public
css
app.css
js
app.js
index.html
CODE:
var express = require('express'),
path = require('path'),
app = express();
// Express Middleware for serving static files
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res) {
res.redirect('index.html');
});
app.listen(8080);
As Tomasz Kasperek pointed out, you need to let Express know that you intend to host these files in a static directory. This is technically called defining static middleware.
This should look something like:
var express = require('express');
var app = express();
// first parameter is the mount point, second is the location in the file system
app.use("/public", express.static(__dirname + "/public"));
It's super simple and I suggest you go the route of making some sort of public folder, rather than bothering to make specific files and folders static.
Then the files would simply be referenced like so from the root index.html:
<link href="public/css/reset.css" rel="stylesheet" type="text/css">
Hope this helps you!
I got it to work by using this syntax
app.use(express.static('public'));
Copy the css and js files under the 'public' directory
and then add the reference in the index.html file
<link rel="stylesheet" href="/css/reset.css">
//we are in ./utils/dbHelper.js, here we have some helper functions
function connect() {
// connect do db...
}
function closeConnection() {
// close connection to DB...
}
//let's export this function to show them to the world outside
module.exports = {
connect(),
closeConnection()
};
// now we are in ./main.js and we want use helper functions from dbHelper.js
const DbHelper = require('./utils/dbHelper'); // import all file and name it DbHelper
DbHelper.connect(); // use function from './utils/dbHelper' using dot(.)
// or we can import only chosen function(s)
const {
connect,
closeConnection
} = require('./utils/dbHelper');
connect(); // use function from class without dot
Related
index.html
<head>
<script src="/main.js"></script>
</head>
Error:
GET http://localhost:3000/main.js
Structure
Project
app.js
view
index.html
main.js
I've tried src="main.js". /view/main.js
Very basic, but dont want to get stuck on this any longer... sigh.
if it helps my app.js file has this:
app.get('/', function (req, res) {
res.sendFile(__dirname + '/view/home.html');
});
So, according to your comments - you are serving only the 'index.html' file instead of whole directory.
Try this code:
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, 'view')));
//... other settings and server launching further
If you want to set serving static files to particular route - extend 'app.use' line with '/your-route', like this:
app.use('/your-route', express.static(path.join(__dirname, 'view')));
After that you can use <script src="main.js"></script> in your index.html
I want a file like index.html to be loaded when the server is created. When I execute the server.js using node, I send a response as text like this res.end("text"). But I want the index.html to load.
I tried to load it using sendFile() in app.get('/getFile') but when I type in the address bar, I get the text for all the urls..even for localhost:3000/getFile.
This is my server.js:
(function(){
var http = require("http");
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var path = require('path');
// app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(express.static(__dirname+'/views'));
var server = http.createServer(function(request, response) {
response.end("text");
});
server.listen('3000');
console.log("Server is listening");
app.get('/getFile',function(request,response){
// response.end('shi');
response.sendFile(path.join('/index.html'));
})
})();
Change the following in your code:
var server = http.createServer(function(request, response) {
response.end("text");
});
to this:
var server = http.createServer(app);
Now, you can serve your static index.html file with this code:
app.get('/', function(req, res, next){
// Serve the index.html file in the root directory of the website.
res.sendFile(path.join('/index.html'));
});
I hope this helps. If you have any questions, let me know.
EDITED
I just made a folder and wrote the following code and I have checked that this is working.
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/indexz.html');
});
app.listen(1339);
console.log('Open this link http://localhost:1337');
Steps
1 Copy the code given above in a new folder and name it whatever you want, name the file server.js
2 go to your cmd and propagate to location of your code and now npm install express
3 now type node server on console
4 open the link that is there on the console.
Note : Make sure there is folder name public and there is a file named
indexz.html in there.
Edited
Regarding proper client side files arrangement
You will have to keep all your files in public folder, first of all and attach them accordingly in your html document.
Example
<!-- Owl Carousel Assets -->
<link href="css/owl.carousel.css" rel="stylesheet">
<link href="css/owl.theme.css" rel="stylesheet">
<script src="js/jquery.min.js"></script>
<script src="angular.js"></script>
<script src="controller.js"></script>
and then within public folder you'll have folders named js and css and in root of the public folder your html files.
Looks your issue is with all the static assets.
In application server like express you have 3 different kind of elements to serve:
static content: this is all html, client side js, css, images and so on
server side templates or views, are documents you assemble with some sort of templating library like handlebars or jade to produce html
api that provide data in xml or more common json format
Your issue is how to serve a static part.
You should add to the static folder of your express app the folder where you build your angular app.
Not just the index.html you need the client side .js, .css and all images the page require.
UPDATE:
Here you could find the express documentation about static content.
UPDATE:
When you add a static folder to the express middleware, you should be able to access your file directly.
For example, if you have 2 files: $project/static/main.js and $project/static/js/my-lib.js, you should use the following urls:
http://127.0.0.1:3000/main.js
http://127.0.0.1:3000/js/my-lib.js
Considering you're executing the node http server on localhost on port 3000.
If you provide a specific path to access the static content, then you have to rewrite your url so.
If you use a line like:
app.use('/staticFolder', express.static('staticFolder'));
Than the urls to the mentioned files will be:
http://127.0.0.1:3000/staticFolder/main.js
http://127.0.0.1:3000/staticFolder/js/my-lib.js
Also pay attention to the path you provide to express.
You should give a proper path, and it's always safer to use absolute paths:
app.use(express.static(__dirname + 'staticFolder'));
or
app.use('/staticFolder', express.static(__dirname + 'staticFolder'));
I recently have the problem that I dont get how the paths for html in node js work. I link my index.html's scripts as normal - relative to the index.html's file (node.js file and index.html are in the same directory "res.sendFile(__dirname + '/index.html');"). But if I open it up in the Browser executed with node js it just stats "cant GET blabla" for the scripts. Instead opening it up by just clicking index.html without node js those paths work! How do I have to write html paths for node js?
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
port = Number(process.env.PORT || 3000),
server.listen(port);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
Thanks for your time! :)
Look at this:
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
You have told Node "When the browser asks for / give it index.html".
What happens when the browser asks for someScript.js?
You haven't told Node what to do then.
(You'll probably want to find a library for serving up static files rather than explicitly handling each one individually).
you should configure express to server static files, for example, put all the static files under a directory called 'public'
var express = require('express');
var app = express();
var path = require('path');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
ExpressJS to Deliver HTML Files
Render HTML file in ExpressJS
You can use
app.use(express.static(path.join(__dirname, "folder-name")));
Usually i put all my static files in a separate folder named "assets"
The I set up a static route as shown below:enter code here
app.use('/assets', express.static('assets'));
When you write:
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
It will only serve index.html file, not the other js scripts and stylesheets which you have added in your html.
There are 2 ways to solve that:
For both of them, I would suggest to use 'path' module.
Solution 1:
var path = require('path')
app.get('/path/to/js/foo.js',function(req,res){
res.sendFile(path.resolve(__dirname,'/path/to/js/foo.js')
})
app.get('/path/to/css/bar.css',function(req,res){
res.sendFile(path.resolve(__dirname,'/path/to/css/bar.css'))
})
and so on for every .css and.js file you have added in your index.html.
Solution 2:
You can create a public dir in your project's root dir. Inside which all your img, css and js files will be there.
Next,
var path = require('path')
app.use(express.static('public'))
app.get('/',function(req,res){
res.sendFile(path.resolve(__dirname,'/index.html')
})
I have a simple doubt but can't figure it out. I am starting node js app,from a localhost location and through the response i am sending a html file. But its node loading the script file which is inside the html.
Node js file
var express = require('express');
var app = express();
var ExpressPeerServer = require('peer').ExpressPeerServer;
app.get('/', function(req, res, next) {
console.log("before redirection");
res.sendfile('index.html'); });
var server = app.listen(9000);
var options = {
debug: true
}
app.use('/api', ExpressPeerServer(server, options));
server.on('connection', function(id) {
console.log("In Server connection")
});
server.on('disconnect', function(id) {
console.log("server Disconnected")
});
Html File
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://cdn.peerjs.com/0.3/peer.js"></script>
<script type = "text/javascript" src="script.js"></script>
</head>
<body>
<h1>ha ha this is Webrtc</h1>
</body>
</html>
script.js
function webRtcInit() {
alert("Inside Script")
}
$(document).on('ready', webRtcInit());
When i normally run the html file its loading the script file. But when i send the file through node js and load the script, I am getting the error , that it cannot get the script file, Why is this happening...?
Thanks
I am seeing few problems in your code:
this renders your html page, similarly, you need one for script.js.
app.get('/', function(req, res, next) {
console.log("before redirection");
res.sendfile('index.html');
});
either specific:
app.get('/script.js', function(req, res, next) {
console.log("before redirection");
res.sendfile('index.html');
});
or generic:
app.use(express.static('static')); // now place your static files in the static folder.
unrelated to the problem at hand, but, in script.js, it is webRtcInit not webRtcInit() :
$(document).on('ready', webRtcInit);
A node.js server does not serve any files by default (this is different that some other web servers). So, any file that you want it to serve must have a route for it or some type of middleware that handles it.
So, your code does have a route for /, but when the browser parses the index.html file that you return from that route and then tries to load script.js from your node.js server, you don't have a route for that and the server will return a 404 (not found).
The solution is to create a route for script.js. Since it's a static resource, you can probably use the express.static capability to serve all your static files. You can read about serving static files in express here.
Before I ask the question here is the folder structure of my node.js express app:
/home
server.js
index.html
/app
/routes
public.js
/public
/css
main.css
This is what I have in server.js:
// ROUTING FOR STATIC CONTENT
var public_dir = __dirname + '/public';
app.use(express.static(public_dir));
// INITIALIZE ROUTER
var public_router = express.Router();
// IMPORT PUBLIC ROUTES
require('./app/routes/public')(public_router, public_dir);
// REGISTER ROUTES
app.use('/', public_router);
This is what I have in /app/routes/public.js:
var path = require('path');
module.exports = function(public_router, public_dir) {
public_router.get('/new', function(req, res) {
res.sendFile(path.join(public_dir, 'index.html'));
});
public_router.get('/popular', function(req, res) {
res.sendFile(path.join(public_dir, 'index.html'));
});
public_router.get('/popular/today', function(req, res) {
res.sendFile(path.join(public_dir, 'index.html'));
});
}
Inside index.html I call css file like this:
<link rel="stylesheet" href="css/main.css">
The problem:
When I visit mydomain.com/new and mydomain.com/popular, css file is loaded and page is rendered properly. However when I visit mydomain.com/popular/today, css file is not loaded properly. In chrome dev tools I see that browser is trying to load css from popular folder which is incorrect.
Any ideas or comments would be appriciated.
Thanks in advance!
Change <link rel="stylesheet" href="css/main.css"> to <link rel="stylesheet" href="/css/main.css">.
Note the prefixing /. This will make the browser to start search in the root of the tree instead of using relative paths.