My folder hierarchy is as follows;
public
----index.html
src
----server.js
when I run the code
var express = require('express');
var app = express();
var serv = require('http').Server(app);
var net = require('net');
var path = require('path');
var port = 3000;
app.use('/../public/', express.static(path.join(__dirname + '/../public/')));
app.get('/', function(req,res){
res.sendFile(__dirname + '/../public/index.html');
});
serv.listen(3000, function(){
console.log('port ' + port + ' is started to being listened')
});
var io = require('socket.io')(serv,{});
it returns forbidden error. How can I reach a file in another subfile?
First of all, what I thought solved it actually didn't solve because I am running multiple projects to understand the basics and I was confused. But now everything is clear. What I am actually trying to do is trying to use express to divide everything to folders. As I didn't know much about http, I watched a lot of videos and finally, I figured it out after watching official introduction video of express on youtube.
Here again what I am trying to accomplish;
-localhost
--public
---index.html
--src
---all server js files and other files that will concern game programming.
As I was trying to reach above, I couldn't manage to do it. What did actually do the trick is;
creating a variable that specifies 'public' directory which is another sub directory under localhost and use it as static which was simple from the beginning but as I didn't know much, I wasn't able to use it after studying few tutorials. As Michael mentioned above, I didn't even need following lines;
app.get(publicDir, function(req, res){
res.sendFile('index.html');
})
All I did was;
var publicDir = require('path').join(__dirname, '/../public');
app.use(express.static(publicDir));
app.use('/../public/'
doesn't really make sense. This parameter is representing the request URL. You can't listen for request URL's which are in the hierarchy somewhere else but not inside your root folder.
Remember that app.use('/' equals a request URL like http://localhost:3000 - meaning this is the absolute basis of the website - the so called root. So where should '/../public' point to? There is no URL with which you could reach such an address.
If you write app.use('/public' it will listen for requests on http://localhost:3000/public
But of course you can send files located in a file structure like you have. So probably what you wanted is:
app.use(express.static(__dirname + '/../public'));
in order to search the static files in a folder structure like:
public
-styles.css
-script.js
-index.html
server
-currentscript.js
where you could access static files like http://localhost:3000/styles.css
You can also completely remove this controller:
app.get('/', function(req,res){
res.sendFile(__dirname + '/../public/index.html');
});
static files like HTML are already served by the Express static files controller mentioned above.
This is enough to access your index.html by calling http://localhost:3000
Related
I am new to nodeJS server area, need help in understanding how to work with REST API (using express) and deploy the angular application over a singe node server and same ports.
By deploying i want to understand if user hit below url http://localhost:8000/<page_name> then the specified page should open.
And is user hit below url using get or post request
http://localhost:8000/api/<api_name> then a json or a text will be returned.
How to run both the thing over a single node server.
Lets assume, you have all your static files in the /public folder of you app. Generally spoken, if you are using express.static, you should also get your index.html because this is handled by default for each directory.
In your case, as you are using Angular, the routing is handled from the client side (SPA). You should only have one single index.html after building your Angular app. All files from your dist folder should then be placed into your /public folder. Then you need to make sure, that initial file serving provides your index.html like so:
In this example static files are served first, then your API and if nothing is found, you are getting back you index file.
const express = require('express');
const app = express();
// serve static files
app.static(__dirname + '/public'));
// serve your API
app.get('/api/welcome', function (req, res) {
res.send('Welcome');
});
// fallback routing (server side handling)
app.get(/.*/, function (req, res) {
res.sendFile(__dirname + ‘/public/index.html‘
});
app.listen(3000);
Next time please make sure, to give all necessary information in your question ;-)
With the help from Sebastian, so far I can find a solution but its not working when i am hitting URL for different pages.
const express = require('express');
const app = express();
app.use(express.static('public'))
Please provide your suggestions.
I'm very new to NodeJS, and I'm currently playing around with it (and websockets), so this question might be a bit dumb. Anyway, I'm following a tutorial which has given me a simple app.js containing the following:
var fs = require('fs')
, http = require('http')
, socketio = require('socket.io');
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-type': 'text/html'});
res.end(fs.readFileSync(__dirname + '/index.html'));
}).listen(8080, function() {
console.log('Listening at: http://localhost:8080');
});
socketio.listen(server).on('connection', function (socket) {
socket.on('message', function (msg) {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
});
In my index.html I'm trying to load some js and css files, but I can't seem to load them. The files are inside a js folder which is in the same directory as my app.js and index.html, and I'm trying to load them like so:
<script src="/js/script.js"></script>
If I look at the response from the request in my browser, it's returning the content of index.html.
Again, sorry if this question is silly, but I'm stuck and have no clue where to look.
Thanks!
A web server in node.js does not serve ANY files by default (unlike some other web servers). So, if you want js files to be served, you have to define a web server route that will serve them. The code you show returns index.html for all incoming requests coming into that http server so, it should be no surpise that when a request comes in for /js/script.js, your web server sends out index.html.
A typical framework to use with node.js for web serving is Express and it has express.static() that can be used to define a route that will cover all your static files or all files in a particular directory. You could, of course, code your own static file handling or find some other module to do that also. The point is that you have to write or configure some code to serve your static resource files. That is not done for you automatically by the node.js http server.
you can specify to the server in which folder to look for what
for static files such as css, images you can use
public directory, you can provide your custom directory, but it's better to use public ,same goes for views
always require
const PATH = require('path')
app.use(express.static(PATH.join(__dirname, 'public')));
for template files such as .ejs, .html, .jade use
app.set('views', PATH.join(__dirname, 'views'));
So I'm new to node and trying to learn how to use the express library with it. However, the problem I'm trying to figure out is why the files in my /public folder do not seem to be served as static content.
Here's my code:
var http = require('http');
var port = process.env.port || 1337;
var express = require('express');
var handlebars = require('express3-handlebars');
var path = require('path');
var application = express();
application.use(express.static(path.join(__dirname, 'public')));
application.engine('handlebars', handlebars({ defaultLayout: 'main' }));
application.get('/', function(req, res){
res.render('index.handlebars', { someProp: 3 });
});
application.listen(port);
And my directory structure:
/
- server.js (the above referenced file)
/ Views
- index.handlebars
/ Layouts
- main.handlebars
/ public
- ServeMe.txt
My understanding was that application.use(express.static(path.join(__dirname, 'public'))); was supposed to configure the server to respond to any request under the public folder with that resource if found. What am I doing wrong? Funnily enough, it was easier to configure handlebars as the view engine than to get this public folder working =D
EDIT: The full URL I am trying to request:
http://localhost:1337/public/serveme.txt
I've tried case sensitivity (which should be a non-issue), and that also did not work.
The full URL I am trying to request: http://localhost:1337/public/serveme.txt
That's your problem. Anything inside the directory you designate as static content is made available directly from the base URL. You need to request http://localhost:1337/serveme.txt instead.
If you want to only serve static files from /public you can pass a string as the first argument:
application.use("/public", express.static(path.join(__dirname, 'public')));
From the Express API reference
app.use(express.static(__dirname + '/public'));
This line serves your public folder at your app's root URL, meaning the following requests are valid and don't give a 404 error.
// GET /javascripts/jquery.js
// GET /style.css
// GET /favicon.ico
app.use takes an optional first argument as well that allows you to specify which request URL you want to serve content at. This first argument defaults to "/", meaning your static content will be served at the base URL. If you want your static content to be served not at the root level, like your code currently does, check out the following example (again taken from the docs)
app.use('/static', express.static(__dirname + '/public'));
This line serves your public folder again, but at your app's /static URL, making the following requests valid without a 404 error.
(Example URL: http://localhost:1337/static/anythingInYourPublicFolder)
// GET /static/javascripts/jquery.js
// GET /static/style.css
// GET /static/favicon.ico
What URLs are you trying to load? You should not include "public" in your URLs, so curl -v 'http://localhost:1337/ServeMe.txt'.
This is the code that I see everywhere for a simple static web server using node.js and express:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8080);
My question is how does express know when the request is for a static page vs. a dynamic page? For example, why would /index.html be served from the public folder and not from dynamic templates?
Thanks.
You can think of the routes you define as a chain of checks on the path defined in the URL. Express iterates one by one through each check looking for a match; once it finds one, it executes that callback.
In this case, express.static is defining a bunch of path checks for each file in the public directory. If you app.use(express.static(__dirname + '/public')); before your app.get('/index.html', function(req, res) { ... code, and there is an index.html file in there, it will use the static file over the dynamic one.
That's basically it.
I would like to know if it is possible to specify a subdirectory for the filesystem root or the document root for requests of static resources (if there's any such distinction) in node.js.
I know that I can do it by concatenating an absolute path from the root, but I'm wondering if it can be done on an application-wide level.
I haven't found anything in the documentation supports it, but perhaps I'm overlooking it.
EDIT: I should mention that I'm not interested in using a 3rd party library at this point.
Check out expressjs
http://expressjs.com/guide.html#configuration
Specifically
app.use(express.static(__dirname + '/public', { maxAge: oneYear }));
Express/connect has a 'static' middleware for this use case. There are other smaller packages just for static file serving, however, express is nice and well maintained.
The API does not allow you to do what you're asking for directly. You will need to use string concat.
I've tried the following script with nodejs and works well. it takes the current path as document root to serve.
app.js
var http = require('http');
var express = require('express');
var app = express();
app.use(express.static('./'));
var server = http.createServer(app);
server.listen(8080,'127.0.0.1',function() {
console.log('listen to 127.0.0.1:8080');
});
the reference is here:
http://expressjs.com/starter/static-files.html