I deployed node js application to AWS EBS. When I run the app, i get the error " 502 Bad Gateway " nginx/1.6.2 . This is what i found out in the log.
env.elasticbeanstalk.com/"
2015/04/21 10:52:01 [error] 3807#0: *86 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.4.86, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8081/", host: "clinicaltrials-env.elasticbeanstalk.com"
This is my package.json file
{
"name": "Clinical_Trial_Analytics",
"version": "1.3.2",
"private": true,
"scripts": {
"start": "node main.js"
},
"dependencies": {
"express": "3.0.6",
"stylus": "0.31.0",
"jade": "0.27.7",
"mongodb": "1.2.7",
"moment" : "1.7.2",
"emailjs": "0.3.3",
"json2html": "1.0.0"
},
"engines": {
"node": "0.12.0",
"npm": "1.1.65"
}
}
This is my main.js file
var express = require('express');
var http = require('http');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 8080);
app.set('views', __dirname + '/server/views');
app.set('view engine', 'jade');
app.locals.pretty = true;
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: 'super-duper-secret-secret' }));
app.use(express.methodOverride());
app.use(require('stylus').middleware({ src: __dirname + '/client' }));
app.use(express.static(__dirname + '/client'));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
require('./server/router')(app);
http.createServer(app).listen(app.get('port'), function(){
console.log("Clinical Trials server listening on port " + app.get('port'));
})
I am unable to figure out the issue. Is it with the node version or any other problem? Thanks in advance.
It's important to add the Node command at Configuration Modify software section of your beanstalk app, I can see in your app you are using the command start, so use it as node command, "npm start" that will start your app correctly, this also happens when use the folder and file bin/www to start the Nodejs server.
Related
Hi Guys, I have created a little project of Mern stack. I am deploying it correctly on Heroku. But as soon as I am checking her on Heroku after deploying, then Failed to load resource: the server responded with a status of 503 (Service Unavailable) error is coming.
But as soon as I run heroku local in cmd after deploying then it is working correctly. I am giving below the heroku setup code. Please guide me. please ........
package.sjon file of backend
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "npm install && node index",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"dependencies": {
"config": "^3.3.1",
"express": "~4.16.1",
"express-fileupload": "^1.1.7-alpha.3",
"mongoose": "^5.9.12",
"nodemailer": "^6.4.6"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Index.js file of backend
var express = require('express');
var path = require('path');
const connectDB = require('./config/db')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var studentRouter = require('./routes/student')
var app = express();
connectDB();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('client/build'))
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
app.use('/', indexRouter);
app.use('/', studentRouter);
app.use('/users', usersRouter);
if (process.env.NODE_ENV == "production") {
app.use(express.static('client/build'))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
}
var port = process.env.PORT || '8000';
app.listen(port, () => {
console.log(`server run port ${port}`);
})
module.exports = app;
All these codes are absolutely correct. I had a problem creating a cluster in mongodb atlas. The problem was that I had selected add current ip address while creating the cluster. Whereas I had to select allow from anywhere. So now I have selected the book. And now it is doing the right thing.
In my case, changing network access form anywhere in my MongoDB cluster, fixed the problem.
Also, don't forget to hit restart all dynos.
I receive an 'Unable to Connect' error in my browser when trying to connect to my Node Express application. At (my servers ip address) 1.1.1.1:5000. The application works fine in my development environment but not on my AWS EC2 Linux server.
The Node Express app works on my computer in dev
Port 5000 is allowing incoming TCP. I tested and confirmed this with a smaller application (https://hackernoon.com/deploying-a-node-app-on-amazon-ec2-d2fb9a6757eb).
I confirmed my Node Express application is running . (I am using pm2)
PM2 keeps restarting my Node Express app at ~14s
I tried to curl from my machine to hit port 5000, I received a connection refused error curl: (7) Failed to connect to 1.1.1.1 port 5000: Connection refused
UPDATE
Instead of starting the application with pm2 start app.js I started it with npm start and I the app is hosted at port 5000 successfully.
I can go to 1.1.1.1:5000 and am returned API is running
I use js fetch api to call the backend at 127.0.0.1:5000 and receive a Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:5000/pickTicket/21780482. (Reason: CORS request did not succeed).
2
TypeError: NetworkError when attempting to fetch resource. (*Note: My api is on the same server as my nginx/react app)`
My application starts with app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var compression = require('compression');
var fetch = require('node-fetch');
var pickTicketRouter = require('./routes/pickTicket');
var kdlRouter = require('./routes/kdl')
console.log('Creating API')
var app = express();
app.use(cors());
app.options('*', cors());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(compression());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('API is running\n');
});
app.use('/pickTicket', pickTicketRouter);
app.use('/kdl', kdlRouter)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
/bin/www
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('api:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '5000');
console.log('Listening on port: ', port);
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(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);
}
package.json
{
"name": "api",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"dev": "nodemon ./bin/www"
},
"dependencies": {
"compression": "^1.7.4",
"cookie-parser": "~1.4.4",
"cors": "^2.8.5",
"debug": "~2.6.9",
"express": "~4.16.1",
"forever": "^1.0.0",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"morgan": "~1.9.1",
"mssql": "^5.1.0",
"node-fetch": "^2.6.0",
"sequelize": "^5.11.0",
"tedious": "^6.2.0"
},
"devDependencies": {
"nodemon": "^1.19.1"
}
}
I expect to see get a response from the api but instead got a CORS error.
I have a few questions regarding the different environments. Is your DEV environment hosted in AWS? If not, I would look at AWS Security Groups to make sure to have the correct TCP protocol for your application.
Also, did you deploy this EC2 into the default VPC or did you create your own VPC?
If you have created a VPC, it could be a routing issue or network level issue.
I was calling pm2 start on app.js instead of bin/www
I have tried number of "Error R10" Solutions, but it doesn't solve the problem for a simple Hello World like Nodejs app with server.js, package.json, index.html and node_module
Hereby adding server.js, package.json and error log
Currently trying this app on free heroku acount
Is it necessary to upload nodejs app on github to host it on heroku
server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var port = 3000;
var app = express();
// Set Static Folder
app.use(express.static(__dirname));
// Body Parser MW
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
var env = process.env.NODE_ENV || 'development';
if ('development' == env) {
app.use(express.static(__dirname + '/'));
} else {
app.use(express.static(__dirname + '/'));
}
app.get("/", function(req, res){
res.render("index.html");
});
app.listen(port, function(){
console.log("Server started ..!");
});
package.json
{
"name": "es1",
"version": "1.0.0",
"description": "eS",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.16.0",
"express": "^4.14.0"
}
}
Attaching heroku logs:
https://drive.google.com/open?id=0B4XtAe7mRM6UVllTQWh1dmplZk0
Change the value of port as follows:
var port = process.env.PORT || 3000;
For my express app I want to use Parse to handle all my data. As Parse's hosting options for web apps seem very limited (caped at 500 files and 500MB), I want to use Heroku to host my app. I have managed to set up my express app on Heroku, but can not quite figure out how to get access to my Parse app in it. I've searched around, but there does not seem to be too much documentation on this, and I am struggling to get it to work.
Here is my index.js for my express app:
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.get('/', function(request, response) {
response.render('pages/public');
});
app.get('/login', function(request, response) {
response.render('pages/login');
});
// Clicking submit on the login form triggers this.
app.post('/login', function(req, res) {
Parse.User.logIn(req.body.username, req.body.password).then(function() {
// Login succeeded, redirect to homepage.
res.redirect('pages/loggedin');
},
function(error) {
// Login failed, redirect back to login form.
res.redirect('pages/login');
});
});
In app.post('/login'I have the Parse function I would use to log in users, but as Parse is not connected it just throws an error. How do I let my Express app get data from Parse?
My package.json files looks like so:
{
"name": "node-js-getting-started",
"version": "0.1.4",
"description": "A simple Node.js app using Express 4",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"ejs": "^2.3.1",
"express": "~4.9.x",
"body-parser": "1.13.x"
},
"engines": {
"node": "0.12.2"
},
"repository": {
"type": "git",
"url": "https://github.com/heroku/node-js-getting-started"
},
"keywords": [
"node",
"heroku",
"express"
],
"license": "MIT"
}
Thanks for any help!
Another hour of googling and I came across these links which proved useful:
https://medium.com/#spacekid/getting-started-with-parse-node-js-express-b2c79798cc7d
http://blog.parse.com/learn/engineering/the-javascript-sdk-in-node-js/
Before using Parse.User.logIn() and so on (or any other node.js module), you must make sure you actually include it like you include bodyParser module.
For example:
var Parse = require('node-parse-api').Parse;
Have a look at this module: Node Parse API
This is common SO question but didn't get the solution. So I am again putting it here.
Here is app.js
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
require('./routes/sockets.js').initialize(server);
here is sockets.js inside routes folder
var io = require('socket.io');
exports.initialize = function(server) {console.log('init called');
io = io.listen(server);console.log('io');
io.sockets.on("connection", function(socket){console.log("connected");
socket.send(JSON.stringify({type:'serverMessage',message: 'Welcome to the most interesting chat room on earth!'}));
socket.on('message', function(message){
message= JSON.parse(message);
if(message.type == "userMessage")
{
socket.broadcast.send(JSON.stringify(message));
message.type = "myMessage";
socket.send(JSON.stringify(message));
}
});
});
};
Inside sockets.js console.log('init called'); console.log('io'); is printing well. When i run this app using npm start is got following error:
npm WARN package.json application-name#0.0.1 No repository field.
npm WARN package.json application-name#0.0.1 No readme data.
> application-name#0.0.1 start D:\Applications\New folder\node\chat
> node app.js
init called
info - socket.io started
io
Express server listening on port 3000
GET / 200 312ms - 511
http.js:707
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:707:11)
at ServerResponse.res.setHeader (D:\Applications\New folder\node\chat\node_m
odules\express\node_modules\connect\lib\patch.js:59:22)
at next (D:\Applications\New folder\node\chat\node_modules\express\node_modu
les\connect\lib\proto.js:153:13)
at Function.app.handle (D:\Applications\New folder\node\chat\node_modules\ex
press\node_modules\connect\lib\proto.js:198:3)
at Server.app (D:\Applications\New folder\node\chat\node_modules\express\nod
e_modules\connect\lib\connect.js:66:31)
at Manager.handleRequest (D:\Applications\New folder\node\chat\node_modules\
socket.io\lib\manager.js:564:28)
at Server.<anonymous> (D:\Applications\New folder\node\chat\node_modules\soc
ket.io\lib\manager.js:118:10)
at Server.EventEmitter.emit (events.js:117:20)
at HTTPParser.parser.onIncoming (http.js:2051:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:122:23
)
When i access localhost:3000 in browser all it happens. I am using node version v0.10.10, express 3.4.4.
Got the solution!! It was because of some version mismatch. Here is the dependency that i used
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "3.4.4",
"socket.io": "0.9",
"jade": "*"
}
}