as part of my learning i wanted to deploy my app to nodejitsu. Its running fine on my local server, but on nodejitsu all i get is
Cannot GET /
I thought it may have something to do with the NODE_ENV set to production on the server, but i never touched this on my local server. I changed it on nodejitsu to development but still i cant get it to work.
After commenting all the code i think the problem is in my index.js which i show below:
var express = require('express');//the framework
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//var session = require('express-session');
var methodOverride = require('method-override');
var passport = require("passport");//for authentication
var LocalStrategy = require('passport-local').Strategy;//local users for passport
var http = require('http');
var path = require('path');
var db = require('./dataBase');//to connect to the db
var userRoles = require('./routingConfig').userRoles;
var accessLevels = require('./routingConfig').accessLevels;
var debug = false;
var db = new db('inmobiliaria', 'localhost', 3306, debug);
require('./passport')(passport, db, debug)
var app = express();
app.set('port', 1337);
app.use(methodOverride());
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }))
//app.use(session({ secret: 'SECRET' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(function (req, res, next) {
var role = userRoles.public;//default role
var username = '';
if (req.user) {
role = req.user.role;
username = req.user.username;
}
res.cookie('user', JSON.stringify({
'username': username,
'role': role
}));
next();
});
app.use('/', express.static(path.join(__dirname + '/../Client/')));
app.use("/lib", express.static(path.join(__dirname + '/../Client/lib/')));
app.use("/ctr", express.static(path.join(__dirname + '/../Client/Controllers/')));
app.use("/media", express.static(path.join(__dirname + '/../Client/media/')));
app.use("/views", express.static(path.join(__dirname + '/../Client/Views/')));
app.use("/srv", express.static(path.join(__dirname + '/../Client/Services/')));
app.use("/dct", express.static(path.join(__dirname + '/../Client/Directives/')));
require('./routes')(app, passport, db);
//require('./emailConfiguration');
http.createServer(app).listen(process.env.PORT || app.get('port'), function (err) {
console.log("Express server listening on port " + app.get('port'));
if (err) {
throw err; // For completeness's sake.
}
});
I investigated about this variable, but im not sure it has something to do with it. This is the url http://horaciotest.jit.su/, in case you want to see it.
Is this configuration? Am i doing something that should not be done?
Thanks for taking your time.
EDIT:
i managed to reduce the error case to a few lines i think. As the guys at nodejitsu suggested, im now trying to use the module node-static to serve static files, but i cant get it to work along express:
this code works on nodejitsu and my local server (or at least doesnt show any errors)
var statik = require('node-static');
var http = require('http');
var path = require('path');
var file = new (statik.Server)(path.join(__dirname + '/../Client/'));//index.html here
http.createServer(function (req, res) {
console.log(path.join(__dirname + '/../Client/'));
file.serve(req, res);
}).listen(8080);
but as soon as i add express, i get the error i mentioned above:
var express = require('express');
var statik = require('node-static');
var http = require('http');
var path = require('path');
var app = express();
var file = new (statik.Server)(path.join(__dirname + '/../Client/'));//index.html here
http.createServer(app, function (req, res) {
console.log(path.join(__dirname + '/../Client/'));
file.serve(req, res);
}).listen(8080);
Can someone tell me why when i add the express app i get the error? it may be what i need to get this to work on nodejitsu, thanks!
I found out what the problem was, hope it helps someone:
My project structure had two folders: one was named Client, where all my html and .js from angular where.
The other folder was WebServer, where i had all my nodejs files.
In order to deploy to nodejitsu, you run a command which is jitsu deploy, this in turn runs another command: npm pack. This command creates a .tgz file with all the data in you nodejs directory excluding the node_modules file and any file that starts with .. Problem is, if you like me have files outside that folder, they wont be included.
The solutions is to move your client folder inside the nodejs one. Everything you need to sent to the server should be in side this folder.
Related
I've tried to write node server which would run React app created by create-react-app. Actually, something strange happens and I don't have any clue what I'm doing wrong (run app as node server/index.js):
export default (app, dirname) => {
app.use(favicon(path.join(dirname, '..','build', 'favicon.ico')));
app.use(express.static(path.join(dirname, '..','build')));
// initialize routers
bootRotes(app);
if (process.env.NODE_ENV === AVAILABLE_ENVIROMENTS.DEVELOPMENT) {
expressBootDev(app, dirname);
} else {
app.get('/*', (req, res) => {
res.sendFile(path.join(dirname, '..', 'build', 'index.html'));
});
}
}
build folder contains build react app which created the following command npm run build
Strange things are happening when after uploading index page it tries to upload static content. For example http://localhost:5000/static/js/2.30e86b6e.chunk.js. Browser just adds / after each static content url and it turns to http://localhost:5000/static/js/2.30e86b6e.chunk.js/ and of course this url doesn't match to express.static middleware.
Moreover, I've checked via Postman, that url GET http://localhost:5000/static/js/2.30e86b6e.chunk.js withot / at the end provides content which is expected.
I work with PRODUCTION env, it means that expressBootDev doesn't have any impacts.
Has anybody has the same issue? I've spent whole day and don't know hopw to fix it.
When I'm creating a simple code in a root app folder with almost the same logic and run as node server.js and it works as expected:
//server.js
const express = require('express');
const favicon = require('express-favicon');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();
app.use(favicon(__dirname + '/build/favicon.ico'));
app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname, 'build')));
app.get('/ping', function (req, res) {
return res.send('pong');
});
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(port);
And I don't see any principal difference
var fs = require('fs');
var express = require('express');
var router = express.Router();
// GET: Sent some basic info for usage
router.get('/', (req, res, next) => {
var fname = __dirname + '/../public/index.html';
var val = fs.readFile( fname, 'utf8', ( err, data) => {
//send can only be called once, write can be called many times,
// in short res.send(msg) == res.write(msg);res.end();
res.writeHeader(200, {"Content-Type": "text/html"});
res.write(data);
res.end();
});
});
module.exports = router;
Here is the example how you can do a static file serving with node.
https://github.com/msatyan/ApiServe1/blob/master/routes/index.js
The full project is
https://github.com/msatyan/ApiServe1
FYI: Node.js with HTTP1 is not an efficient for static file serving by design, I believe HTTP2 support in node has addressed this problem. The reason for inefficiency with HTTP1 is that it has to take the file content read at native layer to JavaScript layer and then send it through HTTP server.
I develop an Nodejs app.I'm using ExpressJS.I've madesome routes to GET data from db.I want to get that data async. In other words i want that requests to be executed on parrallel. I've foundsome examples with callbacks but doesn't help me.Here is an example of request:
var express = require('express');
var app = express();
app.get("/api",function(req,res){
console.log("Test!");
})
How should I write this to be executed async?I want to use node js module async.
This is the example
var app = require('express')();
var path = require('path');
var config = require('dotenv').config({
path: path.join(__dirname + '/../../../.env')
});
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
I am trying to change the below code using connect module and connect-route. Currently it is written in express.
//app.js
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use("/shop/rackOne", rackOne);
app.listen(1000);
//rackOne.js
var express = require('express');
var shoes = require('./shoes.js');
var router = express.Router();
router.all('/stock', shoes);
//shoes.js
function shoes(req, res, next) {
var body = req.body;
}
module.exports = shoes;
Issues which I am facing
Not able to read body data. In connect, no req.body is available.
No .all router is available.
Code change using connect
var connectRoute = require('connect-route'),
connect = require('connect'),
app = connect();
app.use(connectRoute(function (router) {
router.get('/shop/rackOne', rackOne);
});
I am not sure. Is this the correct way to do it. Any help on this will be really helpful.
Well, I'm not sure to understand what you want here, but I'll try to answer.
From the npm page of connect, all I can offer you to try is this :
var connectRoute = require('connect-route');
var connect = require('connect');
var app = connect();
app.use(function yourFunctionFromMiddleware(req, res, next) {
// use req, res as you wish
next();
});
I used connect once, and I used this code, which worked properly for what I needed back there, not sure what you are trying to do here though.
I'm wanting to server index.html as a default, as I'm using angular to handle client side routes.
Here's the structure of my app.
Here is app/app.js
var express = require('express'),
config = require('./config/config'),
bodyParser = require('body-parser'),
app = express(),
router = express.Router();
require('./config/db')(function(db) {
require('./routes/routes')(app, router, null, db);
app.use(express.static(__dirname, '/'));
app.use(bodyParser.json());
app.use('/', router);
app.listen(config.port);
console.log('Listening on port ' + config.port);
});
The only thing in ./routes/routes.js are server side routes. I'm really not sure what I did, but index.html used to load by default and then angular took care of the rest.
I'm new to node/express.
Error I keep getting is "Cannot get/"
Any help is appreciated!
you should use
app.use(express.static(path.resolve('./public')));
on the express configuration
in your route you need to have one to serve your root path
module.exports = function(app) {
// Root routing
var core = require('/controllers/core');
app.route('/').get(core.index);
};
your server controller
exports.index = function(req, res) {
res.render('index'); //assuming that you are using some view engine.
};
I'm new in nodejs. I want to build a rest service with multiple, lets say, categories.
> app.js
var express = require('express')
, http = require('http')
, routes = require('./routes')
, path = require('path');
app = express();
app.use(app.router);
app.get('*',routes.index);
app.listen(3000);
console.log('Express app started on port 3000');
and
> routes/index.js
var sites = [
'sve',
'ice'
];
exports.index = function(req,res){
var url = req.url.split('/');
for (i in sites) {
app.get('/' + sites[i] + '/*',require('./' + sites[i]));
}
};
and
> routes/sve/index.js
module.exports = function(req, res){
console.log('sve')
res.end({category:'sve'});
};
and
> routes/sve/index.js
module.exports = function(req, res){
console.log('sve')
res.end({category:'sve'});
};
when I run "node app" I get "Express app started on port 3000" and the server is running but when I access "localhost:3000/sve/test" I have no response or "localhost:3000/ice/test" or even "localhost:3000/abc/test".
Not even in the console.
What am I doing wrong?
As mentioned in my comment, I think you are looking for a method of using sub-apps (like Rails Engines) do modularize your application. If this is the case, you should use app.use() to mount a sub-app.
There's a good video on it here.
One last thing of relevance that isn't mentioned in the video, you can mount sub-apps relative. For instance:
var subapplication = require('./lib/someapp');
app.use('/base', app.use(subapplication));
This will treat the routes in subapplication as being from the '/base' path. For instance, a route catching '/a' in subapplication, when mounted in this example, will match a request to '/base/a'.