I have an Angular client application that runs entirely in the browser. I am trying to use expressjs to host it. I modeled the server code after the server.js in John Papa's MEAN Hot Towel application that he uses in his Pluralsight Gulp course. This is my server code:
var express = require('express');
var app = express();
var port = process.env.PORT || 7203;
var environment = process.env.NODE_ENV;
console.log('About to crank up node');
console.log('PORT=' + port);
console.log('NODE_ENV=' + environment);
app.get('/ping', function(req, res) {
console.log(req.body);
res.send('pong');
});
console.log('** DEV **');
app.use(express.static('./src/app'));
app.use(express.static('./'));
app.use(express.static('./temp'));
app.use('/*', express.static('./src/index.html'));
app.listen(port, function() {
console.log('Express server listening on port ' + port);
console.log('env = ' + app.get('env') +
'\n__dirname = ' + __dirname +
'\nprocess.cwd = ' + process.cwd());
});
When I navigate to localhost:port/ping, I get pong back. When I navigate to localhost:port/ I get a 404 error. Can someone tell me what I am doing wrong here?
As #tommyd456 stated in the comments above, you need to declare a route for '/', like so:
app.get('/', function(req, res) {
res.send('Hello!');
});
From the express documentation, it seems that express.static targets a folder.
So, replacing app.use('/*', express.static('./src/index.html')); by app.use('/*', express.static('./src')); fix your problem and index.html will be served under 'localhost:port/'
So after many hours of fiddling and reading I replaced this code:
app.use(express.static('./src/app'));
app.use(express.static('./'));
app.use(express.static('./temp'));
app.use('/*', express.static('./src/index.html'));
with this:
app.use(express.static(__dirname));
app.use(express.static(process.cwd()));
app.route('/*')
.get(function(req, res) {
res.sendFile(__dirname + '/index.html');
});
and it appears to have solved the problem
Related
I'm a newbie to express, and I have my app which looks like this:
I have my code like this:
const express = require("express"),
app = express(),
server = require("http").Server(app),
io = require("socket.io")(server)
app.use(express.static(__dirname + "/sign-in/public"))
app.use(express.static(__dirname + "/log-in/public"))
app.get("/sign-in", (req, res) => res.sendFile(__dirname + "/sign-in/public/index.html"))
app.get("/log-in", (req, res) => res.sendFile(__dirname + "/log-in/public/index.html"))
server.listen(8081, () => console.log(`Listening on ${server.address().port}`))
But the problem is, after have executed node server.js, when I go to localhost:8081/log-in, I'll see the sign-up page, same with localhost:8081 and localhost:8081/sign-up. But, I wanna have the log-in page when I go to localhost:8081/log-in... How can I achieve that? What did I do wrong? Thanks
The problem is that you are serving both static path under the same path. Your code should look like this:
const express = require("express"),
app = express();
app.use('/sign-in/', express.static(__dirname + "/sign-in/public"));
app.use('/log-in/', express.static(__dirname + "/log-in/public"));
app.listen(8081, () => console.log(`Listening on 8081`));
Try this it will work fine
app.get('/login', function(req,res){
res.sendfile(__dirname + 'login/public/index.html');
});
Then the reason you are getting this error is because You have defined one Static file route you cannot define it Again this might be the problem i think so i worked 6 months on Mean Stack
can't seem to figure out what the problem with my file structure might be. I'm using Aurelia as a front end and node for the server. I did a join that fixed some of the issues but now I'm getting this error:
Error: (SystemJS) Error: XHR error (404 Not Found) loading http://localhost:3000/src/main.js
Error loading http://localhost:3000/src/main.js
This is my server.js file:
var express = require('express'),
app = express(),
engines = require('consolidate'),
MongoClient = require('mongodb').MongoClient,
assert = require('assert'),
bodyParser = require('body-parser');
app.engine('html', engines.nunjucks);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({ useNewUrlParser: true }));
app.use('/scripts', express.static(require('path').join(__dirname, 'scripts')));
function errorHandler(err, req, res, next) {
console.log(err.message);
console.log(err.stack);
res.status(500).render('error_template', {err: err});
}
MongoClient.connect('mongodb://localhost:27017/', function(err, client) {
assert.equal(null, err);
console.log('MongoDB connected!')
var db = client.db('todos');
app.get('/', function(req, res) {
res.render('index', {});
});
app.use(errorHandler);
});
var server = app.listen(3000, function() {
var port = server.address().port;
console.log("Express server listening on port %s.", port);
});
app.use('/scripts', express.static(require('path').join(__dirname, 'scripts')));
This line of code takes a local folder and makes it available through the express server. You need to do the same thing for your src folder
either with:
app.use('/src', express.static(require('path').join(__dirname, 'src')));
or:
app.use(express.static(require('path').join(__dirname, 'src')));
the first parameter allows you to name the directory it will be served as, which is usually the same.
And even though I didn't include the require('path').join(__dirname,... in the comment, it's good practice to include it.
I know this has been asked a lot but I cant find a solution for mine
my package.json is looking like so:
"main": "server.js",
server.js has
app.post('/', (req, res) => {
console.log('found the route');
})
why is it not logging found the route when I go to localhost:8000??
express is installed etc, just a very basic project
const port = 8000;
app.listen(port, () => {
console.log('We are live on ' + port);
});
Im trying to make a little chat, using NodeJS, Express ans socket.io
For debugging Im using localhost, log4js, and locally it is working fine, socket.io is working with no problem.
But when I try to deploy it on remote server, it isnt working.
Here is a link https://cryptic-fjord-64553.herokuapp.com/
Ofc, I googled, wrote similar topics, tried a lot of stuff, but it isnt working.
Failed to load resource: the server responded with a status of 404
engine.io-client:socket socket error {"type":"TransportError","description":404}
or
engine.io-client:socket socket error {"type":"TransportError","description":0}
My server, app.js includes this:
var express = require('express'),
app = express(),
logger = require('log4js').getLogger();
server = require('http').Server(app),
io = require('socket.io')(server),
this commented block instead server=.. and io=.. above when Im trying to deploy my app on the remote server (heroku)
/*
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
next();
});
var https = require('https'),
socketio = require('socket.io'),
server = https.createServer(app),
io = socketio.listen(server, {log:false, origins:'*:*'});
app.set('port', (process.env.PORT || 5000));
*/
When I try to deploy app on heroku, I comment server.listen.. block below
var pug = require('pug'),
port = 4000;
server.listen(port, '127.0.0.1', ()=>{
var addr = server.address();
logger.level = 'debug';
logger.debug('listening on ' + addr.address + ':' + addr.port);
});
app.use(express.static(__dirname + '/public'));
app.get('/socket.io.js', (req,res)=>{
res.sendFile(__dirname + '/node_modules/socket.io-client/dist/socket.io.js');
});
app.get('/socket.io/socket.io.js', (req,res)=>{
res.sendFile(__dirname + '/node_modules/socket.io-client/dist/socket.io.js');
});
app.get('/jquery.js', (req,res)=>{
res.sendFile(__dirname + '/node_modules/jquery/dist/jquery.min.js');
});
app.set('views', __dirname + '/views');
app.set('view engine', 'pug');
const amazingStuff = 'Its amazing stuff, ',
date = new Date;
app.get('/', (req,res)=>{
res.render('pages/index', {
title: 'main page',
message: date,
showChat: false
});
io.on('connection', (socket)=>{
socket.on('newUserJoin', (userName)=>{
socket.session = {};
socket.session.userName = userName;
socket.session.address = socket.handshake.address;
socket.session.id = socket.id;
socket.broadcast.emit('newUser', socket.session);
socket.emit('user', socket.session)
socket.emit('userLisr', io.length)
logger.info('user ' + socket.session.userName + ' / ip ' + socket.session.address)
logger.info('user count: ' + io.engine.clientsCount)
logger.debug(socket.session)
var clients = io.sockets.connected,
clientList = {};
for (var i in clients){
if(clients[i].session) clientList[i] = clients[i].session;
}
socket.emit('clientList', clientList);
})
//get a new message and share it to all users
socket.on('newMessage', (message)=>{
socket.broadcast.emit('shareMessage', message)
})
})
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
versions:
"devDependencies": {
"nodemon": "^1.11.0"
},
"dependencies": {
"express": "^4.15.3",
"jquery": "^3.2.1",
"log4js": "^2.3.3",
"pug": "^2.0.0-rc.3",
"socket.io": "^2.0.3"
}
client, main.js:
var socket = io();
//var socket = io.connect('https://cryptic-fjord-64553.herokuapp.com/');
and handlers
and here is adding scripts in html(pug), first works locally, commented stuff are attempts I tried to do for deploying on heroku, but it doesnt work.
script(src='/socket.io/socket.io.js')
//-script(src='/socket.io.js')
//-script(src='https://cryptic-fjord-64553.herokuapp.com/socket.io.js')
U cant open the link above and take a look whats going on in the console. There are no warnings regarding client side script, I mean main.js file, so it can connect to the server and main.js knows what is 'io'. So it seems like its ok with links in the html and socket.io connection to the server. So probably its problem in the server side app.js
How can I force it to work on heroku?
I'm a beginner programmer and pretty new to Node.js.
I managed to setup a single static page by using AWS EC2 and Heroku, but I need help making other subpages. ie. mysite/blog or mysite/archive.
I started out with a simple web.js file I got from a sample node app which was:
var express = require('express');
var app = express();
app.use(express.logger());
app.get('/', function(request, response) {
response.send('Hello World!');
});
var port = process.env.PORT || 5000;
app.listen(port, function() {
console.log("Listening on " + port);
All that said was Hello World so I created index.html and changed web.js to this.
var express = require('express');
var fs = require('fs');
var htmlfile = "index.html";
var app = express(express.logger());
app.get('/', function(request, response) {
var html = fs.readFileSync(htmlfile).toString();
response.send(html);
});
var port = process.env.PORT || 8080;
app.listen(port, function() {
console.log("Listening on " + port);
Now that serves index.html instead, but how do I get /blog or /archive to work?
You can add other routes to your code to handle specific URL formats. Make sure the more specific URLs are listed before the general route (/ or *)
// Handle request for blog
app.get('/blog', function(req, res){
res.send('A list of blog posts should go here');
});
// Handle request for archive
app.get('/archive', function(req, res){
res.send('Archive content should go here');
});
// Route for everything else.
app.get('*', function(req, res){
res.send('Hello World');
});
I've got a more lengthy explanation about this here: http://hectorcorrea.com/#/blog/introduction-to-node-js/51