Node JS Express all requests showing 404 - javascript

All requests are showing GET / 404 8.128 ms-13 in console.
I have posted the code below, there is no error in the code. I can run other NodeJS applications. But this is showing 404 in console. It is not even showing the fav icon. It worked once showing Cannot GET / error and the fav icon was visible at that time.
'use strict';
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var logger = require('morgan');
var port = process.env.PORT || 8001;
var four0four = require('./utils/404')();
var environment = process.env.NODE_ENV;
app.use(favicon(__dirname + '/favicon.ico'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(logger('dev'));
app.use('/api', require('./routes'));
console.log('About to crank up node');
console.log('PORT=' + port);
console.log('NODE_ENV=' + environment);
switch (environment){
default:
console.log('** DEV **');
app.use(express.static('./src/client/'));
app.use(express.static('./'));
app.use(express.static('./tmp'));
app.use('/app/*', function(req, res, next) {
four0four.send404(req, res);
});
app.use('/*', express.static('./src/client/index.html'));
break;
}
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());
});

According to http://expressjs.com/starter/static-files.html I think that your route here app.use('/*', express.static('./src/client/index.html')); will use ./src/client/index.html as the base path and append whatever you provide to find a file. For example
/some-file will look for ./src/client/index.html/some-file which is obviously not existed
In case you want to understand it more, the static middleware use https://github.com/pillarjs/send internally to stream file
So you can do this
app.use('/*', express.static('./src/client'));
It will, by default, set / to src/client/index.html, you can change that behaviour by setting index option as specified here https://github.com/expressjs/serve-static
If you want to redirect /* to ./src/client/index.html do this
// first set the static middleware
app.use('/public', express.static('./src/client'));
// then use redirect
app.get('/*', function(req, res, next){
res.redirect('/public/index.html');
});
This setup will redirect everything to public/index.html. If you want to add APIs or other routes, put it before the app.get('/*')

Related

Angular2 + ExpressJs <app-root> dosen't load.

I did read all the other topics but none of the solutions solved my problem.
I write npm start and the server is working as it should but app-root does not it seems like it does not load the client (Angular 2 app).
I just get an empty html page with:
Loading...
(look at my html file down the page)
any idea what can cause it - or any suggested solution ?
Thank you.
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose')
//Set up default mongoose connection
var mongoDB = 'mongodb://localhost/beatblocks';
// Get Mongoose to use the global promise library
mongoose.Promise = global.Promise;
mongoose.connect(mongoDB, function(err) {
if (err){
console.log("error connecting to db...")
}
console.log("connected to database...");
});
// Load Songs Model
require('./models/songs');
const songs = mongoose.model('songs');
// Load Locations Model
require('./models/locations');
const locations = mongoose.model('locations');
// Load users Model
require('./models/users');
const users = mongoose.model('users');
var routeIndex = require('./routes/index');
var routeSongs = require('./routes/songs');
var routeUsers = require('./routes/users');
//var routeLocations = require('./routes/locations');
var app = express();
var router = express.Router();
// Set Static Folder
app.use(express.static(path.join(__dirname, 'views')));
app.use(express.static(path.join(__dirname, '/client/dist')));
app.use(express.static(path.join(__dirname, 'client/src')));
//View Engine
app.engine('ejs', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/', routeIndex);
app.use('/songs', routeSongs);
app.use('/users', routeUsers);
//app.use('/locations', routeLocations);
module.exports = app;
www.js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('beatblocksweb:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
app.listen(port, function(){
console.log('Server started on port '+port);
});
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
my index.html :
<html>
<head>
<title>Beat Blocks</title>
</head>
<body>
<app-root>Loading...</app-root>
<app-header></app-header>
</body>
</html>
my project :

Node.js file server with file index

I have the below code for a file server and I would like to use and html page to show an index of the files that are available for download in the static folder "public1"
I currently can serve an html page if the user explicitly requests it but I can't make it automatically serve the html page. The commented out code is my attempt at serving the html page named "hello" by default. It doesn't work...
How can I make the html page display (by default) to the user that navigates to the ip address in a browser?
How can I make the html file show an index of files in the static folder?
So for this two part question, does anyone know how to do this? Can you point me in the right direction.
var express = require('express');
var server = express();
var port = 10001;
//server.get(__dirname + 'public1', function(req, res) {
// res.send('Hello.html');
//});
server.use(express.static(__dirname + '/public1'));
server.listen(port, function() {
console.log('server listening on port ' + port);
});
The easiest way to do this is by using the serve-index and serve-static middleware that is available for express. The below example code works, just swap out the process.cwd() for whatever directory you'd like to serve.
const express = require('express');
const serveIndex = require('serve-index');
const serveStatic = require('serve-static');
const path = require('path');
const server = express();
const port = process.env.PORT || 3000;
function setHeaders(res, filepath) {
res.setHeader('Content-Disposition', 'attachment; filename=' + path.basename(filepath));
}
const dirToServe = process.cwd();
server.use('/', serveIndex(dirToServe, {icons: true}));
server.use('/', serveStatic(dirToServe, {setHeaders: setHeaders}));
server.listen(port, () => {
console.log('listening on port ' + port);
});

How to use a site to work on localhost with the help of node.js?

I am learning node.js where i am trying to use Google webpage to work on my localhost where its menu items to be removed but its search functionality should work on localhost as it works on website. This I tried working to use google on localhost but on localhost it shows "Can not Get", is this a kind of error or am i doing wrong please guide me that how i can achieve what i want to work. I am using node.js ver5.9.1 on XP.
Thanks in advance.
search.js
var express = require('express'),
app = express();
var bodyParser = require('body-parser');
compression = require('compression');
var NLTunnel = require('node-local-tunnel');
var options = {
remoteHost : 'http://www.google.com/',
localBase : 'http://localhost:3000'
};
NLTunnel.client(options);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(compression());
app.use(express.static('assets/'));
app.listen(3000);
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
compression = require('compression'),
http = require('http'),
server = http.createServer(app);
app.use(bodyParser());
app.use('/', express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(compression());
server.listen(3000);
Try this. This is working on my machine.
I have tried using request and cheerio but i am getting only html page and no any css or js page (if there) and search function is also not working. Is this right to work on and how we can make search functionality to work as usual on localhost.
var httpobj = require('http');
var request = require('request');
var cheerio = require('cheerio');
var all_html;
var url = 'https://www.google.co.in/?gfe_rd=cr&ei=dVHeVuLuG-uK8QeCk6vICw'
request(url, function (error, response, html) {
var $page = cheerio.load(html);
all_html = $page("html");
});
httpobj.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(all_html + ' ');
res.end('');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');

Manipulating Cookies before serving

Scenario
I have a simple NodeJS server using the Express framework. I have some ReactJS pages that I need to serve. No Isomorphic for now.
Before serving, I want to check if the user has a particular cookie and then based on that I want to create a new cookie.
What I tried
Here is the code for my server.js file.
var express = require("express");
var app = express();
var Cookies = require("cookies");
app.use(function(req, res){
var cookies = new Cookies( req, res);
var userCookie = cookies.get("sso");
var isLoggedIn = cookies.get("isLoggedIn");
if(userCookie !== undefined && isLoggedIn === false){
cookies.set("isLoggedIn", true);
}
});
app.use(express.static(__dirname + '/build'));
var port = process.env.PORT || 8080;
app.listen(port, function() {
console.log("Listening on " + port);
});
So I am using express.static for serving static files from my build folder.
I tried moving the app.use(express.static(__dirname + '/build')); line above the previous app.use, but then the code never enters the cookies section.
I tried this simple thing. Even this didn't worked. I can see log hello, but the website isn't working.
var express = require("express");
var app = express();
app.use(function(req, res){
console.log("hello");
});
app.use(express.static(__dirname + '/build'));
var port = process.env.PORT || 8080;
app.listen(port, function() {
console.log("Listening on " + port);
});
There's a problem with your use of cookies. You're checking if isLoggedIn, the cookie value, === false, a boolean value. But cookies are always strings, so the comparison will always be false and you'll never set isLoggedIn to "true".
If your update your code to treat the values as strings it might work. Try something like this:
if(userCookie !== undefined && isLoggedIn !== "true"){
cookies.set("isLoggedIn", "true");
}
As jeremy's answer pointed out, I was using the cookies the wrong way. But that wasn't the core problem. If code would have run, express server would have thrown error. The real problem was that i wasn't calling the next middleware in the application’s request-response cycle. According to the docs
Middleware is a function with access to the request object (req), the
response object (res), and the next middleware in the application’s
request-response cycle, commonly denoted by a variable named next.
I wasn't calling the next.
So the updated running code is:
var express = require("express");
var app = express();
var Cookies = require("cookies");
app.use(function(req, res, next){
var cookies = new Cookies( req, res);
var userCookie = cookies.get("sso");
var isLoggedIn = cookies.get("isLoggedIn");
if(userCookie !== undefined && isLoggedIn !== "true"){
cookies.set("isLoggedIn", "true",{ httpOnly: false } );
}
next();
});
app.use(express.static(__dirname + '/build'));
var port = process.env.PORT || 8142;
app.listen(port, function() {
console.log("Listening on " + port);
});

node.js - express - URL and error handling

i'm new to node.js, so please be indulgently.
I'm just playing around with node.js and the express-module.
I had an idea how to deal with browser-requests and now i have a simple question:
Is this a good idea/practice or is there a better solution to handle that?
var http = require('http');
var express = require('express');
var fs = require('fs');
var app = express();
http.createServer(app).listen(80);
app.get('/*',function(req,res,next){
fs.exists(__dirname + req.url, function (exists) {
if(exists)
{
console.log('Sending ' + __dirname + req.url + "...");
res.sendfile(__dirname + req.url);
}
else
{
console.log(__dirname + req.url + " not found!");
res.send('Sorry, page not found.',404);
}
});
});
Express is based on Connect and as such supports its middleware. And there is a perfect middleware for your situation: static file serving.
app.use(express.static(__dirname + '/public'));
This will serve all files within the /public directory as static files available from the root directory. For routes which are not handled separately and for which no file exists, a 404 error is returned.
Btw. you want to put the listen-call to the end.

Categories

Resources