Nodejs on single page - javascript

I'm new on Nodejs.
I have to do a web app with node js, express, socket.io on an existing website.
I use JXcore on Parallels Plesk panel to execute node.
But when I run js file and I visit any page on the website it returns "Cannot GET ".
If I use express get() function:
var app = require('express')();
var http = require('http').Server(app);
var path = require('path');
app.get('/path/to/index.html', function(req, res){
res.sendfile( path.resolve(__dirname + '/index.html') );
});
http.listen(10500, function(){
console.log('listening on *:10500');
});
it works on /path/to/index.html but every other website page is blocked by the same error "Cannot GET ".
Is there a way to run node only on one page?
Thanks

What your code is doing is defining just one route /path/to/index.html and mapping that to your index.html file. If you want to serve files from a directory, static html/css/js/whatever files, you can use the static method express provides:
app.use("/", express.static(__dirname + '/myHtmlDirectory'));
Change the "myHtmlDirectory" to whatever directory you store your files in and make sure to change the includes to define express:
var express = require('express');
var app = express();
However, if you want all GET requests to point to one single file, index.html for example, you can use the following:
app.get('*', function (req, res) {
res.sendfile( path.resolve(__dirname + '/index.html') );
});

Related

node server.js - Cannot GET /

I am currently working on a project which is a webpage using angular to dynamically change DOM elements. Within the project is a public folder which contains all HTML, CSS, JavaScript and JSON objects. The project must be distributed so I am using node to run from localhost. This is my server.js code:
var express = require('express');
var app = express();
var path = require('path');
app.get('/', function(req,res){
res.sendFile(path.join(__dirname + '/public'));
});
app.listen(8080, function(){
console.log((new Date()) + " Server is listening on port 8080");
});
When I head to localhost:8080 it just says Cannot GET /. Where am I going wrong?
The correct way to serve static files with express is as follows:
//Look for statics first
app.use(express.static(path.join(__dirname, 'public')));
//Return the index for any other GET request
app.get('/*', function (req, res) {
res.sendFile('index.html', {root: path.join(__dirname, 'public')});
});
Edit: on a side note this may be worthwhile to mention that app.get should be the last route declared in node so if you want API endpoints exposed declare them above (before) the final app.get.
You forgot to point to the actual html file you want to display. If you have a index.html in your public directory, just point tot '/public/index.html' . That works (tested it here).
Followed user Muli's answer and all files are now being served correctly. Code here:
var express = require('express');
var app = express();
var path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req,res){
res.sendFile('index.html', {root: path.join(__dirname, './public')})
});
app.listen(8080, function(){
console.log((new Date()) + " Server is listening on port 8080");
});

Loading HTML files in Nodejs

I am trying to load HTML files in nodejs. In public folder, I have two html files test.html and index.html. I would like to use nodejs to showcase the pages, but its working for index.html and for the case of test, it shows an error saying that res.sendFile is not a function.
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 + '/public/index.html'));
});
// viewed at http://localhost:8080
app.get('/test', function(req, res) {
res.sendFile(path.join(__dirname + '/public/test.html'));
});
app.listen(8080);
For serving static files such as JS, CSS, images, html files, you can use the express.static built-in middleware function in Express.
Serving static files in Express
Say if your 'Public' folder has some JS, html files which is required at client side. Then you need do to go like this :-
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
var server = app.listen(8080);

Node JS - HTML Paths

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')
})

How can I serve my web app with Node/Express?

I'm probably going to ask a huge noob question, one of the worst I've ever had asked here, but I'm lost as hell with Node/Express. I've only used Apache servers (typical WAMP/XAMP for testing purposes), so I have absolutely no idea on what I have to do to serve my web app.
My folder tree is the following:
www
nodeserver.js
(more things)
Liteconomy (my web app)
js
css
plugins
templates
index.html
sublime_project
Pretty typical, huh? Well, I've been searching how to serve this app with a simple access like localhost:8080/Liteconomy, or localhost:8080/Liteconomy.html. After that, my angular routing would do the rest, but I just can't serve the app.
I've got this written in nodeserver.js:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(8080, function () {
console.log('Example app listening on port 8080!');
});
app.get('/Liteconomy', function (req, res) {
res.send('Liteconomy/index.html');
});
When I execute it and access to localhost:8080, I get the "Hello world", but when I go to localhost:8080/Liteconomy, I get the following plain text: "Liteconomy/index.html". If I try to access to the index resource directly, I get a "Cannot GET /Liteconomy/index.html" error.
I also tried using the static thingy, but didn't work either.
What am I doing wrong here? I guess I'm just missing something very important.
Do the following, it will resolve your issue.
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// uncomment following if you want to access your app from /liteconomy
//app.use('/liteconomy', express.static(__dirname + '/Liteconomy', {index: "index.html"}));
//This will enable you to access it form '/'
app.use('/', express.static(__dirname + '/Liteconomy', {index: "index.html"}));
// Rest of the stuff
Then if you will visit your URL that you set and port, you'll be able to access.
Using express.static is recommended way of serving static content.
Hope it helps!
You get a plain text answer because you actually ask to do it with the :
app.get('/Liteconomy', function (req, res) {
res.send('Liteconomy/index.html');
});
If you want to send a simple html file like your index.html file, you should use the "sendfile " function :
app.get('/Liteconomy', function (req, res) {
res.sendfile(__dirname + '/Liteconomy/index.html');
});
"__dirname" represents your root directory path and then you simply put your file path.
Hope that helps !
PS : by default express come with jade and ejs template support instead of just using html. I would advise you to take a look at one of them, it can be a great help to construct your application web pages.

NodeJS and express, ENOENT on view file

I've got a weird trouble with my nodeJS app since I refactored it.
The app starts well, API answers correctly but when I try to go to /, I get this error : Error: ENOENT, stat '/views/index.html' in my browser.
I now use this folder tree :
project
front
views
index.html
bower_components
app
node
server.js
And here is the content of my server.js file :
var express = require('express');
var app = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var fs = require('fs');
var nconf = require('nconf');
app.use(express.static(__dirname + '/../front'));
app.use(express.static(__dirname + '/../node_modules'));
app.use(express.static(__dirname + '/../bower_components'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({'extended': 'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({type: 'application/vnd.api+json'}));
app.use(methodOverride());
server.listen(8081);
(...) // some code to define API routes
app.get('/', function (req, res) {
res.sendfile('/views/index.html');
});
I tried to comment app.use(express.static(__dirname + '/../front')); and to call the view using '/front/views/index.html' but the result is the same.
ENOENT means Error NO ENTry which ultimately means it's not able to find your file.
int ENOENT
No such file or directory. This is a "file doesn't exist"
error for ordinary files that are referenced in contexts where they
are expected to already exist.
Your server is attempting to send a file from the root directory of your machine (/views/index.html). You'll probably need to adjust this to fit your file structure.
app.get('/', function (req, res) {
res.sendfile(__dirname + '/../font/views/index.html');
});
I believe you missed to set your views folder.
app.set('views', 'MY_DIR_PATH');
As #Sean3z suggested, I tried to change my sendfile declaration and got another error (Forbidden, sendStream error).
Finally I managed to make it work by changing my static files definition :
app.use('/front', express.static(__dirname + '/../front'));
And by modifying the sendFile : res.sendfile('front/views/index.html');
Strangely, nodeJS understands (but not me :) ) and call the right file at the right place. I just need to correct my calls in the differents file to be ok.
Thanks for the answers.

Categories