I am new to MEAN Stack. and i am using Ubuntu. i installed ejs, express, node etc via Terminal. i made a folder in Documents>NodeTuts and then in in terminal i wrote npm init after the progress i got package.json in nodeTuts and server.js and than i made a folder in nodeTuts named client and then in client>views and in views i made a file index.ejs.
In server.js i wrote:
var express = require('express');
var app = express();
var path = require('path');
var port = process.env.PORT;
app.set('view engine','ejs');
app.set('views', path.resolve(__dirname, 'client', 'views'));
app.get('/', function (req, res){
res.render('index.ejs');
});
app.listen(port, function (){
console.log('SERVER RUNNING... PORT: ' + port);
})`
and in index.js i wrote:
simply HELLO WORLD
but when i opened server.js in Chrome i thought there will be HELLO WORLD but there was server.js code as a text This is what i got
I am learning from Brent Aureli's Tutorials. he is doing all this on windows usng cloudy and i am doing this on Ubuntu!
Please help me It's been 3 days i am stuck in this. Thanks!
You must run server.js via node command like this:
PORT=8080 node server.js
Since you haven't specified port on your server file, you must write it with your node command.
Then, open Chrome and type into address bar localhost:8080 (or other port).
If you don't want to write port every time you run node command, change this line:
var port = process.env.PORT || 8080 // or any other port number
Related
Created the docker file as following:
FROM node:boron
ADD package.json package.json
RUN npm install
ADD . .
EXPOSE 4500
CMD ["node","main.js"]
Building the app:
docker build -t "appname"
Running the app:
docker run -it "appname"
Inside main.js, I have:
var express = require("express");
var app = express();
var path = require('path');
var http = require('http');
var https = require('https');
var nodemailer = require('nodemailer');
var bodyParser = require('body-parser');
var request = require("request");
var port = process.env.PORT || 3001;
app.set('port', (port));
app.listen(app.get('port'), function () {
console.log('Node app is running on port', app.get('port'));
});
//app.use('/', express.static(path.join(__dirname, '/public_html')))
app.use('/', express.static(__dirname + '/public_html'));
app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.urlencoded({
limit: '5mb',
extended: false
}));
app.get('/', function(request, response) {
response.render('public_html/');
});
//app.get('/', function (req, res, next) {
// res.sendFile('/index.html');
//});
app.use('*', function (req, res, err) {
// console.log('error: ', err);
});
when I run the app using docker command 'docker run -it "appname"`, I get the out to console:
Node app is running on port 3001
But when I browse, page is empty or nothing is loaded in the browser/output/view. It is supposed to pick up index.html from response.render('public_html/');
You need to explicitly expose the port which your app is supposed to run on:
docker run -p 3001:3001 your-node-image
Then you can access your container's service on your docker host under http://localhost:3001, because -p 3001:3001 binds the host port 3001 (the first 3001 in the argument) to the container's port 3001 (the second 3001).
EXPOSE from your Dockerfile only describes which ports are exposed by your application (which is in your Dockerfile 4500 and in your program port 3001...? Why are they different?). Publishing ports with -p is also necessary to access the container, see the docs:
The EXPOSE instruction informs Docker that the container listens on the specified network ports at runtime. EXPOSE does not make the ports of the container accessible to the host. To do that, you must use either the -p flag to publish a range of ports or the -P flag to publish all of the exposed ports.
Additionally, the flags -it appear to be useless with your service. You need these flags when you want to have an interactive session, e.g. when you're starting a shell in your container.
See here some more information about port exposal in the official documentation
I try to connect backend (NodeJS, Express) with Frontend (Angular 2), but have a problem.
When I start two servers separately, both client-side and server-side work fine.
In my situation:
localhost:4200 - Angular
localhost:3000 - NodeJS, Express
When I render any static html file in my VIEWS folder, it works correctly, but when I change the content of the html file to Angular Index.html, that uses components, it doesn’t work. I mean, it works, but doesn't load my components.
I suppose that problem is in the configuration, and my index.html doesn't know how to find and load components, but I don’t understand exactly where a mistake might be.
When I try to start both servers at the same port, my frontend part stops working.
I use Angular-CLI, NodeJS, Express and EJS.
My server.js code is:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var tasks = require('./routes/tasks');
var port = 3000;
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view enjine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'views')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use('/', index);
app.use('/api', tasks);
app.listen(port, function () {
console.log('Server started on port ' + port);
});
In the ROUTES folder my index.js code is:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index.html');
});
module.exports = router;
My folders structure:
Picture of foldes
node_modules
routes
ruen-app
views
package.json
server.js
ruen-app is my client (Angular 2) folder.
So, my questions are:
How to connect these two parts?
Is it correct to start two servers at the same time - one for the frontend, another for the backend?
What is the best practice for MEAN applications to start from the scratch? I mean, what is the best way - two servers or one?
Spent 3 days, but found the solution.
On the stackoverflow:
Different ports for frontend and backend. How to make a request?
Angular-CLI proxy to backend doesn't work
There might be a very simple solution to this question, but I am not able to find answer online and due to my practice with node I can't figure it out either.
I'm trying to set up a simple server.js file that listens on port 80 and serves /dist/index.html file when users enter root address, so example.com
This is my project structure
dist/
index.html
bundle.js
node-modules/
package.json
server.js
You can create a static server with express:
server.js
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/dist'));
app.listen(8080, function() {
console.log('Listening on port: ' + 80);
});
You simply run node server.js to get the static server. This app can also be deployed.
http-server is a simple method of serving from your file system. Install that, then just run http-server -p X in the command line in your project folder, substituting your port number for X
I have a Node.js/Express.js app running on my server that only works on port 3000 and I'm trying to figure out why. Here's what I've found:
Without specifying a port (app.listen()), the app runs but the web page does not load.
On port 3001 (app.listen(3001)) or any other port that is not in use, the app runs but the web page does not load.
On port 2999, the app throws an error because something else is using that port.
On port 3000, the app runs and the web page loads fine.
I know that Express apps default to port 3000. But strangely, my app only runs when I explicitly make it run on port 3000 (app.listen(3000)).
I found this on line 220 of /usr/bin/express:
app.set(\'port\', process.env.PORT || 3000);
Which is doing as previously stated: setting the port to what is specified or to 3000 if nothing is specified.
How could I make my app work on a different port such as 8080 or 3001?
Thanks!
Edit: Code Sample (Very Simple Node/Express App)
var express = require("express");
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
// Only works on 3000 regardless of what I set environment port to or how I set [value] in app.set('port', [value]).
app.listen(3000);
The following works if you have something like this in your app.js:
http.createServer(app).listen(app.get('port'),
function(){
console.log("Express server listening on port " + app.get('port'));
});
Either explicitly hardcode your code to use the port you want, like:
app.set('port', process.env.PORT || 3000);
This code means set your port to the environment variable PORT or if that is undefined then set it to the literal 3000.
Or, use your environment to set the port. Setting it via the environment is used to help delineate between PRODUCTION and DEVELOPMENT and also a lot of Platforms as a Service use the environment to set the port according to their specs as well as internal Express configs. The following sets an environment key=value pair and then launches your app.
$ PORT=8080 node app.js
In reference to your code example, you want something like this:
var express = require("express");
var app = express();
// sets port 8080 to default or unless otherwise specified in the environment
app.set('port', process.env.PORT || 8080);
app.get('/', function(req, res){
res.send('hello world');
});
// Only works on 3000 regardless of what I set environment port to or how I set
// [value] in app.set('port', [value]).
// app.listen(3000);
app.listen(app.get('port'));
In bin/www, there is a line:
var port = normalizePort(process.env.PORT || '3000');
Try to modify it.
Try this
$ PORT=8080 node app.js
Try to locate the bin>www location and try to change the port number...
The default way to change the listening port on The Express framework is to modify the file named www in the bin folder.
There, you will find a line such as the following
var port = normalizePort(process.env.PORT || '3000');
Change the value 3000 to any port you wish.
This is valid for Express version 4.13.1
Just a note for Mac OS X and Linux users:
If you want to run your Node / Express app on a port number lower than 1024, you have to run as the superuser:
sudo PORT=80 node app.js
In the lastest version of code with express-generator (4.13.1) app.js is an exported module and the server is started in /bin/www using app.set('port', process.env.PORT || 3001) in app.js will be overridden by a similar statement in bin/www.
I just changed the statement in bin/www.
Noticed this was never resolved... You likely have a firewall in front of your machine blocking those ports, or iptables is set up to prevent the use of those ports.
Try running nmap -F localhost when you run your app (install nmap if you don't have it). If it appears that you're running the app on the correct port and you can't access it via a remote browser then there is some middleware or a physical firewall that's blocking the port.
Hope this helps!
The line you found just looks for the environmental variable PORT, if it's defined it uses it, otherwise uses the default port 3000. You have to define this environmental variable first (no need to be root)
export PORT=8080
node <your-app.js>
If you want to show something you're connected on 3000
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
I hope that will be helpful to you
Answer according to current version of express
If you talk about the current version of express, if you run app.listen() to start listening without specifying port, Express will chose a random port for your application, to find out about which port it is currently running on use
app.listen(0, () => {
console.log(app.address().port)
}
should output the port of your app. Moreover that first parameter 0 can be totally ignored but is not recommended
In app.js, just add...
process.env.PORT=2999;
This will isolate the PORT variable to the express application.
I am using the minimist package and the node startup arguments to control the port.
node server.js --port 4000
or
node server.js -p 4000
Inside server.js, the port can be determined by
var argv = parseArgs(process.argv.slice(2))
const port = argv.port || argv.p || 3000;
console.log(`Listening on port ${port}...`)
//....listen(port);
and it defaults to 3000 if no port is passed as an argument.
You can then use listen on the port variable.
Make sure you are running from that folder of your application, where you have the package.json.
I think the best way is to use dotenv package and set the port on the .env config file without to modify the file www inside the folder bin.
Just install the package with the command:
npm install dotenv
require it on your application:
require('dotenv').config()
Create a .env file in the root directory of your project, and add the port in it (for example) to listen on port 5000
PORT=5000
and that's it.
More info here
If you are using Nodemon my guess is the PORT 3000 is set in the nodemonConfig.
Check if that is the case.
My app.js has the following contents:
var express = require('express')
, http = require('http')
, path = require('path')
, redis = require('redis')
, client = redis.createClient();
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
require('./routes')(app);
client.on("connect", function () {
console.log("Client on connect");
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
All I'm attempting is to use the node_redis library to connect with a Redis instance. Both Node.js, and Redis are installed locally. One thing I'd like to point out is that I created, and attempting to run this project with Jetbrains' Webstorm (since I would like an IDE that provides me with some debugging). The string 'Client on connect' is logged to the console, but my app pretty much crashes every single time with 'Process finished with exit code 139'. I tried running the app via the command line, and the app doesn't crash. The worst part is that there is no stack trace of any sort when the app fails to run in Webstorm. Does anyone have any clue on what the issue is or where I could find more information that is logged regarding this error code?
Also, just so that we're on the same page: My Redis server is up and running, and receiving a constant stream of data from another custom webapp. I was able to fire up redis-cli, and verify that Redis actually contains any data.
If you're using a Unix-type OS, 139 means "128 + the signal number your Node process crashed on". So in your case, that signal was 11, which on most Unices means SIGSEGV. In other words: the Node process crashes on some sort of invalid memory reference.
In my experience, when you get these kinds of errors while starting processes from IDE's (or other apps), it usually means the IDE is passing some sort of environment which causes the crash. You could try and attach GDB to the running Node process (but before connecting to it, causing the crash) to find out what's causing it.
Another solution: if you can change the node executable that Webstorm will start, you could try to make a shell script which wraps Node and prints some debugging info. Something like this:
#!/bin/sh
echo "ENVIRONMENT: $ENV"
sleep 1
/path/to/actual/node "$#"
That would output the environment variables which are passed to the Node executable. From there, you could try and unset any variables which look suspicious:
unset STRANGE_VARIABLE
You place those in the script above, before starting the Node executable.