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?
Related
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');
});
I have a public folder in which I put an angular2 app. Now I am trying to setup an express server with a catchall route that always returns index.html. To be clear - according to this question I need to map all of my routes to index.html.
If I access the base server URL (localhost:10001), everything works as expected. But when I go to a route(let's say localhost:10001/landing), and refresh the page, I get the following error:
Error: ENOENT: no such file or directory, stat
'/Users/shooshte/express-test/index.html' at Error (native)
This is my server configuration:
var express = require('express');
var static = require('serve-static');
var server = express();
// middleware
server.use(express.static(__dirname + '/public'));
// routes
server.use('*', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
var port = 10001;
server.listen(port, function() {
console.log('server listening on port ' + port);
});
What am I doing wrong?
You're missing the public directory in the path to index.html:
res.sendFile(__dirname + '/public/index.html');
i think you don't have your index.html in either public or your root folder /Users/shooshte/express-test/
this is the only resion you are getting this error
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'));
I've configured express as follows:
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.sendfile(__dirname + '/3in1/src/index.html');
});
app.get('/index.html', function(req, res) {
res.sendfile(__dirname + '/3in1/src/index.html');
});
/* serves all the static files */
app.use(express.static(__dirname + '/3in1/src/'));
var port = process.env.PORT || 80;
app.listen(port, function() {
console.log("Listening on " + port);
});
I have my css in a file under the folder
/3in1/src/css/
Which all make it to the browser OK. The problem is when the request is made to my javascript files, which, are located throughout the following folder like so:
/3in1/bower_components/library-name/library.js
/3in1/bower_components/library-two/library_two.js
etc...
etc..
etc.
The problem is I get a 404. The links in my index look something like this:
<script type="text/javascript" src="../bower_components/PreloadJS/lib/preloadjs-0.4.1.combined.js"></script>
<script type="text/javascript" src="../bower_components/jquery/dist/jquery.js"></script>
<script type="text/javascript" src="../bower_components/jquery-mousewheel/jquery.mousewheel.js"></script>
What am i doing wrong? I thought that it would recognize the relative paths I'm using, i.e. "../" but I thought wrong, I guess! What is the correct way to do this?
The solution for this simple example was to just add the following line of code:
app.use('/bower_components', express.static(__dirname + '/3in1/bower_components/'));
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.