getaddrinfo ENOTFOUND error - node.js

I had a perfectly running nodejs server on an EC2 instance of Amazon AWS. By mistake, I missed a couple of payments and the service was halted. When I paid and brought the account up to date, I found the server was back in place and was already running.
However, since then, my very first request has started returning the "getaddrinfo ENOTFOUND" error and am not able to check any other request either. This is weird, since the first line in the code to check the health of the server (refer to index.html below) return the desired "All Ok" result. But the subsequent requests gives the ENOTFOUND error. Any help in this will be very much appreciated.
FYI, I have tried stopping and restarting the server, didn't help.
Here is the code of the base file:
require('newrelic');
var express = require('express'),
bodyParser = require('body-parser'),
oauthserver = require('oauth2-server');
var multer = require('multer');
var upload = multer({ dest: '../uploads/' });
var controllernew = require('./controllers/controllernew');
var app = express();
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
/***************************************************************
********FOLLOWING REQUEST RETURNS ALL OK AS DESIRED*************
****************************************************************/
app.get('/index.html', controllernew.index);
app.oauth = oauthserver({
model: require('./models/modeloauth'),
grants: ['password'],
debug: true,
accessTokenLifetime: 31536000
});
/******************************************************************
*******GETTING ENOTFOUND ERROR FOR THE FOLLOWING REQUEST***********
*******************************************************************/
app.get('/userOTP/:userid/username/:username', controllernew.getUserOTP);
app.all('/oauth/token', app.oauth.grant());
app.all('*', app.oauth.authorise());
app.use(app.oauth.errorHandler());
app.post('/uploadimagenew', upload.single('upload'), function(req, res) {
var controllernew = require('./controllers/controllernew');
controllernew.createImage2(req, res, function(){
console.log(req.file);
console.log(req.body.csvlistevents);
var strArray = req.body.csvlistevents.split("|");
console.log(strArray[3]);
})
});
routes = require("./routes/items")();
app.use(routes);
var server = app.listen(8080, function(){
console.log('server started at ' + server.address().port);
});

Related

node.js what is causing error 400 bad request

I was adding some code to my node.js web app. I added this one feature, and then it threw an error 400. I removed it by hitting Ctrl-Z, but it still threw error 400. Then, I made a test.js that was the simplest implementation of express, and it is still getting error 400. Here is my code for test.js:
const app = require("express")();
const http = require("http").createServer(app);
const url = require('url');
app.get("/", function(req, res)
{
res.sendFile(__dirname + "/test.html");
});
http.listen(3001, function()
{
console.log("--listening on port 3001");
});
I have checked to make sure I am typing in the correct url, with the correct port. I think something got cached and is screwing it up, since it works if I clear my cache or use curl. Any ideas?
Use process.cwd() instead of __dirname which is causing error and generating 404.
process.cwd() will return the directory where node is intialized. It returns absolute path where you started the node.js process.
const app = require("express")();
const http = require("http").createServer(app);
const url = require('url');
const path = require('path');
app.get("/", function(req, res)
{
// res.sendFile(__dirname + "/test.html");
res.sendFile(process.cwd() + "/test.html");
});
http.listen(3001, function()
{
console.log("--listening on port 3001");
});
or You can also resolve the path of __dirname
const app = require("express")();
const http = require("http").createServer(app);
const url = require('url');
const path = require('path');
app.get("/", function(req, res)
{
__dirname=path.resolve();
res.sendFile(__dirname + "/test.html");
});
http.listen(3001, function()
{
console.log("--listening on port 3001");
});
After some more research (and thanks to comments), I finally found the problem!
I was storing too much stuff in cookies, and it exceeded the maximum amount of 4KB.

Express req.query always empty

I was using express route like this and I want my urls to contain query strings initially.
app.get('/', function(req, res){
res.render('index', {});
});
app.get('/us01', function(req, res){
console.log('query: '+JSON.stringify(req.query));
res.render('templates/us01', {});
});
app.get('/benchmark', function(req, res){
res.render('templates/benchmark', {});
});
However, I never get my query strings printed no matter what query strings I append after /us01. For example, "localhost:9200/us01?a=1" req.query should get me {a:1}, correct? Is this a common thing? What am I missing here?
My app.js
"use strict";
var express = require('express');
var expApp = express();
var http = require('http').Server(expApp);
var path = require('path');
var bodyParser = require('body-parser');
// all environments
expApp.set('port', process.env.PORT || 5555);
expApp.set('views', __dirname + '/views');
expApp.set('view engine', 'ejs');
expApp.use(bodyParser.urlencoded({ extended: true }));
expApp.use(bodyParser.json());
expApp.use(express.static(path.join(__dirname, 'public')));
//----------------ROUTES--------------------------//
require("./routes/route.js")(expApp);
http.listen(expApp.get('port'), function(){
console.log('Node-Server listening on port ' + expApp.get('port'));
});
My indexController.js has :
$stateProvider
.state('us01', {
url: '/us01',
templateUrl: '/us01'
}).state('benchmark', {
url: '/benchmark',
templateUrl: '/benchmark'
})....
This simple code:
const express = require('express');
const app = express();
app.get('/us01', function(req, res) {
console.log(req.query);
res.send("ok");
});
app.listen(80);
Then, accessed by http://localhost/us01?a=1 produces this output in the console:
{ a: '1' }
Or, if I use:
console.log('query: ' + JSON.stringify(req.query));
Then, I see this in the console:
query: {"a":"1"}
So, clearly something else is wrong in your code.
"localhost:9200/us01?a=1" req.query should get me {a:1}, correct?
It should get you query: {"a":"1"} if the code you show is running on port 9200 on localhost.
Is this a common thing?
No. Something other than the code you show is busted because there's nothing wrong with just that bit of code.
What am I missing here?
Things to examine:
Are you getting any output in the console when you hit any of your expected routes?
Can you prove that your server is running and your browser is hitting your route handlers?
If you just do console.log(req.query), what output do you get?
Are you absolutely sure that you've killed any prior servers and started the server that corresponds to the code you show. People sometimes get fooled by a prior version of the server that is still running and doesn't actually contain the code they think they are running.
Are you 100% sure you are running your server on the desired port that matches the port in the URL you are using.
When all else fails, sometimes a computer reboot will make sure no prior versions of anything are still running.

routing using connect - similar to express

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.

Why is request body undefined in one route?

I'm having some troubles trying to stablish a REST API with nodeJS and express. The following code defines two routes, "stores" and "user".
Surprisingly, the route to "/user" is working nice but when a request arrives to "/stores" the request body appears undefined. I've searched for a solution but nothing seems to work for me.
Both controllers have the same structure.
What am I doing wrong?
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
methodOverride = require("method-override"),
mongoose = require('mongoose');
// Connection to DB
mongoose.connect('mongodb://localhost/appDB', function(err, res) {
if(err) throw err;
console.log('Connected to Database');
});
// Middlewares
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
//Import models and controllers
var userModel=require("./models/user.js")(app,mongoose);
var storeModel=require("./models/store.js")(app,mongoose);
var usersController=require("./controllers/users.js");
var storesController=require("./controllers/stores.js");
//Router options
var router=express.Router();
router.route('/stores')
.get(storesController.getNearestStores);
router.route('/user')
.post(usersController.addUser);
app.use(router);
//Start server
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
Thank you very much.
P.S.:First time with nodejs and express(and even mongo)
This is because there is no body on a GET request in the http standard. Only POST and PUT.
What you want to do instead is use a query string
get
/stores?location=mystore
this way on your callback you have access to req.query
req.query
{
location: 'mystore'
}
HTTP GET with request body
This gave me the solution, get requests don't accept parameters under HTTP standard.

Run NodeJS app on nodejitsu, all i get is "cannot get /"

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.

Resources