express.static breaks nodejitsu application - javascript

I have no idea why this happens, but when I add a static path to my app I get an error on page of a hosting company I am using "nodejitsu" saying that application is not working, the line I am referring to is commented out in a code snippet below 'server.js' that is on the same level as my 'public' directory. I'm trying to think of a work around or other solution to define my public directory, but no luck so far, as I don't understand what could be causing an error. application uses node.js with dependencies including express and socket.io, latest versions.
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
//app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
io.on('connection', function (socket) {
});

The express term is not defined because you didn't save it.
You will need to do something like this:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));

Related

Access localhost:3000 through localhost/myproject/index.html

I am new to node.js and I would like to learn if I could access the node.js port (3000) by writing the url of the index.html. I followed this tutorial to create a chat app, but I have the problem I mentioned above.
I want to be able to write localhost/myproject/index.html instead of localhost:3000 on my browser.
My server-side javascript code is this:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Is there something I should change here? Any help would be appreciated.
If you want run your project as domain name instead of localhost:3000 then just follow this link
https://www.digitalocean.com/community/tutorials/how-to-set-up-apache-virtual-hosts-on-ubuntu-14-04-lts
To be able to access your path without defining a port you would need to use port 80 or port 443 for https.
http.listen(80, function(){
console.log('listening on *:80');
});
Concerning the path you should adjust the routing parameter, also have a look at static files in express js.
app.get('/myproject/index', function(req, res){
res.sendFile(__dirname + '/index.html');
});

Can't utilize static files w/ node.js and express

I'm trying to use node.js and express to create a chat client, but as soon as I try to use external CSS or JS files, I run into GET errors.
Currently I have index.js as:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
And in my index.html I use:
<script src="/dropdown.js"></script>
<link rel="stylesheet" type="text/css" href="/style1.css">
to link the files in the HTML.
My code structure is
index.js
index.html
public
style1.css
dropdown.js
I've looked at a bunch of other solutions on stackoverflow and none of them worked. I've tried various combinations of using express.static/app.static and various combinations of linking CSS/JS files in the html file. All of them result in GET errors.
Instead of:
app.use(express.static(__dirname + '/public'));
Try this:
app.use(express.static(path.join(process.cwd(), '/public')));
Created project with exactly same code and file structure like yours, and it worked. Make sure you have written all file names correctly and all that "obvious" stuff. And if that doesn't help can you provide some error messages?

Winjs app cant connect nodejs socket.io server

I'm build an WP app using HTML5/js/CSS, and today i got a problem. I create a NodeJs server using socket.io fot chat. My server code:
var express = require('express')
, routes = require('./routes')
, http = require('http');
var app = express();
var mongodb = require('mongodb');
var url = 'mongodb://localhost:27017/chat';
var MongoClient = mongodb.MongoClient;
app.configure(function(){
app.set('port', process.env.PORT || 3456);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
var io = require('socket.io').listen(server)
, guestNumber = 1
, nickNames = {}
, numuser = 0;
io.set('log level', 1);
io.on('connection', function (socket) {
...
});
In my app, i use: var socket = io.connect('myipserver:3456/');
IT NOT CONNECT to my server, but when i use browser to connect my ip server, it normal, and in my app, it got error: XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd.
In package.appxmanifest, i checked Internet ( Client & Server ) Capabilities.
So, do i miss something in my app ? Plz help.
After some Googling I saw this question that has the same error code as your app. Seems to me that this error code says that the app does not see the server. So I don't think it's a socket-related error.
Try making a simple AJAX request to your server (with jQuery: $.get(myipserver:3456/some-static-file)). If it works, then it's something with the socket communications, otherwise the app does not see the server at all. Good point to start from, I guess.

Express and Cheerio/JSDOM

I am trying to get Cheerio to work with Express.
I'd like to be able to manipulate the dom from the server, but all I have found is web scraping..
There are some requirements..
At the moment, I am able to run multiple app.listen(port); statements, and use multiple servers.
I'm trying to append <script>alert("test);</script> to every single page sent by express.
I've created the express server: (Assuming Path is a predefined variable)
var express = require('express');
var app = express();
app.get('/', function (req, res) {
app.use(app.static(Path));
res.sendFile(Path + "/index.html");
});
app.listen(Port);
Can you guys provide me with a working example to append this to the page. Is there a way to get this to work in real time?
Thanks!
Here's a quick/simple example with no error handling:
var express = require('express');
var fs = require('fs');
var cheerio = require('cheerio');
var app = express();
app.get('/', function (req, res) {
fs.readFile(Path + '/index.html', function(err, data) {
var $ = cheerio.load(data);
$('body').append('<script>alert("test");</script>');
res.send($.html());
});
});
app.listen(Port);
I just tested that locally and it worked as expected. Be sure to test err inside the readFile callback in your real implementation and handle things appropriately if the file isn't found or there's an error reading it.

Basic webserver with node.js and express for serving html file and assets

I'm making some frontend experiments and I'd like to have a very basic webserver to quickly start a project and serve the files (one index.html file + some css/js/img files). So I'm trying to make something with node.js and express, I played with both already, but I don't want to use a render engine this time since I'll have only a single static file, with this code I get the html file but not the assets (error 404):
var express = require('express'),
app = express.createServer();
app.configure(function(){
app.use(express.static(__dirname + '/static'));
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.listen(3000);
Is there a simple way to do it (in one file if possible) or Express requires the use of a view and render engine ?
I came across this because I have a similar situation. I don't need or like templates. Anything you put in the public/ directory under express gets served as static content (Just like Apache). So I placed my index.html there and used sendfile to handle requests with no file (eg: GET http://mysite/):
app.get('/', function(req,res) {
res.sendfile('public/index.html');
});
Following code worked for me.
var express = require('express'),
app = express(),
http = require('http'),
httpServer = http.Server(app);
app.use(express.static(__dirname + '/folder_containing_assets_OR_scripts'));
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
app.listen(3000);
this loads page with assets
You could use a solution like this in node.js (link no longer works), as I've blogged about before.
The summarise, install connect with npm install connect.
Then paste this code into a file called server.js in the same folder as your HTML/CSS/JS files.
var util = require('util'),
connect = require('connect'),
port = 1337;
connect.createServer(connect.static(__dirname)).listen(port);
util.puts('Listening on ' + port + '...');
util.puts('Press Ctrl + C to stop.');
Now navigate to that folder in your terminal and run node server.js, this will give you a temporary web server at http://localhost:1337
Thank you to original posters, but their answers are a bit outdated now. It's very, very simple to do. A basic setup looks like this:
const express = require("express");
const app = express();
const dir = `${__dirname}/public/`;
app.get("/", (req, res) => {
res.sendFile(dir + "index.html");
});
app.get("/contact", (req, res) => {
res.sendFile(dir + "contact.html");
});
// Serve a 404 page on all other accessed routes, or redirect to specific page
app.get("*", (req, res) => {
// res.sendFile(dir + "404.html");
// res.redirect("/");
});
app.listen(3000);
The above example is if you want to serve individual HTML files. If you were serving a single page JS app, this would work.
const express = require("express");
const app = express();
const dir = `${__dirname}/public/`;
app.get("*", (req, res) => {
res.sendFile(dir + "index.html");
});
app.listen(3000);
If you need to serve other static assets from within a folder, you can add something like this before you start defining the routes:
app.use(express.static('public'))
Let's say you have a js folder inside public like: public/js. You could include any of those files inside of your html files using relative paths. For example, let's say /contact needs a contact.js file. In your contact.html file, you can include the script as easy as:
<script src="./js/contact.js"></script>
Building off of that example, you can do the same with css, images etc.
<img src="./images/rofl-waffle.png" />
<link rel="stylesheet" href="./css/o-rly-owl.css" />
Hope this helps everyone from the future out.

Categories

Resources