nodejs express apps in small orange - node.js

I am new to "A Small Orange" and I am trying to run an express app in small orange following this link
I first created the following directory structure
/home/user/servercode/myapp with tmp directory and app.js file
/home/user/public_html/clientCode/myapp with .htaccess
/home/user/servercode/myapp/tmp contains an empty restart.txt file
In /home/user/servercode/myapp, I ran
npm init
npm install express --save
This is my app.js. Pretty much same as the one in the link mentioned in the post
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World Express App');
});
if (typeof(PhusionPassenger) != 'undefined') {
console.log( 'Example app listening with passenger' );
app.listen('passenger');
} else {
console.log( 'Example app listening with 3000' );
app.listen(3000);
}
.htaccess has 644 permission level and contains this
PassengerEnabled on
PassengerAppRoot /home/user/serverCode/myapp
SetEnv NODE_ENV production
SetEnv NODE_PATH /usr/lib/node_modules
When I try to access myapp, I get this error
Cannot GET /myapp/ and 404 in browser console
I could get a normal nodejs application running without express with the below content in app.js
var http = require('http');
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
});
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
But not able to get express app running

You need to add route in you application as :
app.get('/myapp', function(req, res){...});

Related

Node.js - static files are getting replaced with HTML code

Problem
I just started out with Node.js my plan was to first set up a Server with some basic HTML and static files(css,js).
But when i try to Serve the static files with express.js or even without express the js/css code is getting replaced from my index.html code. Without Node.js everything seems to work fine i even tried it with flask in python which worked fine too.
Are there any common reasons for this?
Node.js code
var http = require("http");
var fs = require("fs");
var express = require("express");
var app = express();
app.use("/", express.static("public"));
http
.createServer(function(req, res) {
fs.readFile("index.html", function(err, data) {
if (err) {
res.writeHead(404, { "Content-Type": "text/html" });
return res.end("404 Not Found");
}
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
return res.end();
});
})
.listen(8080);
Pictures
So even though you are using express to serve static files, you are not using express as server instead of that you are making a manual server which serves index.html for EVERY request.
http
.createServer(function(req, res) {
fs.readFile("index.html"....);
})
.listen(8080);
What this code means is create a server, and for each request read the index.html file and serve this
So when the request is http://localhost:8080/css.css it doesn't discriminate.
I would recommend reading about creating servers in node a little more. But the solution is use express as server.
var http = require("http");
var fs = require("fs");
var express = require("express");
var app = express();
app.use("/", express.static("public"));
app.listen(8080, ()=>{
console.log('Server started');
})
This will work just fine GIVEN that index.html IS IN A FOLDER NAMED PUBLIC
From the doc,
For example, use the following code to serve images, CSS files, and
JavaScript files in a directory named public:
app.use(express.static('public'))
Now, you can load the files that are
in the public directory:
Note, if your files are in your project root you can use:
app.use("/", express.static("."));

NodeJS, Express. Cannot upload static content

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.

nodejs, Express Cannot GET /

I try to run simplest Express code on Cloud server
var express = require('express');
var app = express();
app.get('/test', (req, res) => res.send('Hello '));
app.listen( 3000 );
I am getting the Apache 404 error : GET /cood180119/projExpress1/demo1/test HTTP/1.0, Cannot GET /cood180119/projExpress1/demo1/test
I have noticed that my url is http://77.xx.xx.xx/cood180119/projExpress1/demo1/test
while error logs shows IP : 88.xx.xx.xx.
How to resolve?
I have a node hello world example, which is working with the following url:
http://77.xx.xx.xx/node-hello-world-master/
where the file is in public_html/node-hello-world-master/app.js,
but does not work with http://77.xx.xx.xx:3000/
const http = require('http');
http.createServer(function(request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end("Hello, World!\n port= ' + process.env.PORT);
}).listen(process.env.PORT); //is says that port is undefined
I set the port=3000 in environmental node variables.
After this, i can get the port number echoed , but i still can not access webpage using ttp://77.xx.xx.xx:3000/
Seems firewall is configured wrong.
I think you are requesting the wrong URL.
app.get('/test', (req, res) => res.send('Hello '));
app.listen( 3000 );
this will always produce a route as follows
'http://ip:3000/test
why do you use cood180119/projExpress1/demo1 in your URL. I don't see any route defined for that.
Your route
app.get('/test', (req, res) => res.send('Hello '));
make sure that the URI (or the path in this case /test) of the request you want to capture exists.
My problem:
The name of html file was not exactly "index.html"
So, I renamed it and it worked perfectly!
app.use(express.static('public'));
Note: public is a folder inside my server directory witch contains index.html and styles.css.

Node.js: Sending file in same directory

I hope this question isn't too ridiculous.
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req,res){
res.sendFile('index.html');
});
http.listen(3000,function(){
console.log('/','listening on *:3000');
});
I am running linux mint, and whenever I try to run this locally I get the following error:
Error: ENOENT, stat 'index.html'
at Error (native)
I believe it has something to do with the directory. The index.html file is in the same folder as the index.js file. I've searched around and couldn't find this exact error in this case so am kind of confused. Am I putting in the wrong directory for the
app.get('/', function(req,res){
res.sendFile('index.html');
});
You need to specify exactly where your index.html file is located. Try using the following code snippet
var app = require('express')();
var http = require('http').Server(app);
var path = require('path');
app.get('/', function(req,res){
res.sendFile(path.join(__dirname, 'index.html'));
});
http.listen(3000,function(){
console.log('/','listening on *:3000');
});

Deploy node.js app on heroku succeeds but doesn't work

I have a very simple, straight-forward node.js app [1] I want to deploy on heroku. Although I'm able to deploy it, the page can't be accessed in the browser.
I followed the advices from the 'Getting Started with Node.js on Heroku' guide [2]. When I run the application using node index.js locally, I'm able to access the application at http://localhost:8080/index.jade, however, when I try to access it on heroku at http://immonow.herokuapp.com:8080/index.jade it would throw me a ERR_CONNECTION_REFUSED HTTP error code.
How I deployed my app:
git commit -am "made changes" // commit changes
git push origin master // push to git
heroku create // create heroku app
git push heroku master // push to heroku
heroku ps:scale web=1 // start workers
My node.js server:
#!/usr/bin/env node
var http = require('http')
, jade = require('jade')
, static = require('node-static')
, jadeRe = /\.jade$/
, path = process.argv.slice(2)[0]
, fileServer = new static.Server(path || '.')
http.createServer(function (req, res) {
if (req.url.match(jadeRe)) {
res.writeHead(200, {'Content-Type': 'text/html'})
res.end(jade.renderFile('.' + req.url, {
filename: '.' + req.url.replace(jadeRe, '')
}))
} else {
req.addListener('end', function () {
fileServer.serve(req, res)
}).resume()
}
}).listen(8080)
Any help would be appreciated.
[1] https://github.com/takahser/immonow
[2] https://devcenter.heroku.com/articles/getting-started-with-nodejs#introduction
Since I was not able to get it to work using the http package, I decided to use express instead. As for the port, I had to do it as follow
var port = process.env.PORT || 3000;
app.listen(port);
in order to get it to work [1].
Here is my full working server:
/**
* Module dependencies.
*/
var express = require('express');
// Path to our public directory
var pub = __dirname + '/public';
// setup middleware
var app = express();
app.use(express.static(pub));
app.use("/css", express.static(__dirname + '/css'));
app.use("/font", express.static(__dirname + '/font'));
app.use("/img", express.static(__dirname + '/img'));
app.use("/js", express.static(__dirname + '/js'));
app.use("/video", express.static(__dirname + '/video'));
// Set our default template engine to "jade"
// which prevents the need for extensions
// (although you can still mix and match)
app.set('view engine', 'jade');
app.get('/', function(req, res){
res.render('index');
});
app.get('/*', function(req, res){
console.log(req.url.replace("/",""));
res.render(req.url.replace("/",""));
});
// change this to a better error handler in your code
// sending stacktrace to users in production is not good
app.use(function(err, req, res, next) {
res.send(err.stack);
});
/* istanbul ignore next */
if (!module.parent) {
var port = process.env.PORT || 3000;
app.listen(port);
console.log('Express started on port 3000');
}
[1] see: Node.js port issue on Heroku cedar stack
Things I had to do..
Create a Procfile in the root directory (a file literally called Procfile, no extension).
Inside Procfile, type:
web: node server.js
Add a script and engine to package.json
"scripts": {
"start": "node server.js"
}
"engines": {
"node": "8.9.3"
}
Update port in server.js
var port = process.env.PORT || 8080;
And why..
To explicitly declare what command should be executed to start your app. Heroku looks for a Procfile specifying your process types
For the script, if no Procfile is present in the root directory during the build process, your web process will be started by running npm start. For the engine, to specify a Node version that matches the runtime you’re developing with and want to use on Heroku.
Heroku already assigns your app a port and adds it to the env, so you can't set the port to a fixed number.
Resources:
https://devcenter.heroku.com/articles/getting-started-with-nodejs#introduction
https://devcenter.heroku.com/articles/troubleshooting-node-deploys
https://devcenter.heroku.com/articles/deploying-nodejs

Resources