RangeError: Invalid status code: 0 - javascript

I am having an issue where I am getting the following error code when attempting a POST request on this application (bearing in mind I am a beginner node.js/js programmer):
Error:
[20:22:28] [nodemon] starting `node app.js`
Running server on 3000
Mon, 27 Jun 2016 19:22:31 GMT express deprecated res.send(status, body): Use res.status(status).send(body) instead at routes\edit.js:35:25
c:\Users\Matt\WebstormProjects\ghs_restart\node_modules\mongodb\lib\utils.js:98
process.nextTick(function() { throw err; });
^
RangeError: Invalid status code: 0
at ServerResponse.writeHead (_http_server.js:192:11)
at ServerResponse._implicitHeader (_http_server.js:157:8)
at ServerResponse.OutgoingMessage.end (_http_outgoing.js:573:10)
at ServerResponse.send (c:\Users\Matt\WebstormProjects\ghs_restart\node_modules\express\lib\response.js:204:10)
at ServerResponse.json (c:\Users\Matt\WebstormProjects\ghs_restart\node_modules\express\lib\response.js:249:15)
at ServerResponse.send (c:\Users\Matt\WebstormProjects\ghs_restart\node_modules\express\lib\response.js:151:21)
at c:\Users\Matt\WebstormProjects\ghs_restart\routes\edit.js:35:25
at c:\Users\Matt\WebstormProjects\ghs_restart\node_modules\mongodb\lib\collection.js:416:18
at handleCallback (c:\Users\Matt\WebstormProjects\ghs_restart\node_modules\mongodb\lib\utils.js:96:12)
at c:\Users\Matt\WebstormProjects\ghs_restart\node_modules\mongodb\lib\collection.js:705:5
app.js:
var express = require('express');
var router = express.Router();
var app = express();
var bodyParser = require('body-parser');
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
var path = require('path');
var port = process.env.PORT || 3000;
var index = require('./routes/index');
var edit = require('./routes/edit');
app.use('/', index);
app.use('/edit', edit);
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'jade');
app.set('views', 'views');
app.listen(port, function (err) {
console.log("Running server on", port);
});
module.exports = index;
The following is my edit.js route, where I believe the issue is occurring:
var express = require('express');
var router = express.Router();
var app = express();
var bodyParser = require('body-parser');
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
var path = require('path');
var port = process.env.PORT || 3000;
var index = require('./routes/index');
var edit = require('./routes/edit');
app.use('/', index);
app.use('/edit', edit);
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'jade');
app.set('views', 'views');
app.listen(port, function (err) {
console.log("Running server on", port);
});
module.exports = index;

I had a similar error message just now and managed to solve the problem by changing:
res.status(statusCode);
to:
if (statusCode >= 100 && statusCode < 600)
res.status(statusCode);
else
res.status(500);
or just:
res.status(statusCode >= 100 && statusCode < 600 ? err.code : 500);
I.e. make sure you aren't trying to set an invalid HTTP status code somewhere.
It's likely this is the issue but it looks like you've accidentally duplicated the app.js code instead of pasting the edit.js code in the question.

This case also happen when we have validation error on form save and we are using res.redirect instead of res.render method
for example-
Please Use
res.render('users/add', {
countries: countries
});
instead of (it's wrong statement for node)
res.redirect('/users/add', {
countries: countries
});

I had the same problem which I solved by using:
res.send('0')
instead of
res.send(0)

for me the issue was that i had not created my upload directory and it returns me the error. may be you should consider to create your ./upload directory first, because of permission issues on linux.

Related

Node JS Middleware Function Required

When I run the following:
const express = require('express');
const bodyParser = require('body-parser');
const routes = require("./routes.js");
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(routes);
var port = process.env.PORT || 3000;
app.listen(port);
I get:
TypeError: app.use() requires a middleware function.
The console says the error occurs at the u in app.use(routes);. However if I run:
var express = require('express');
var bodyParser = require('body-parser');
var clientSessions = require('client-sessions');
var routes = require("./routes");
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/', express.static('./'));
app.use('/js', express.static('./public/js'));
app.use('/CSS', express.static('./public/CSS'));
app.use('/images', express.static('./public/images'));
app.use('/views', express.static('./public/views'));
app.use(clientSessions({
secret: 'ugkgdiuwgbkbgjwjkgvo'
}));
app.use(routes);
var port = process.env.PORT || 3000;
app.listen(port);
From a different project, that project works fine which leads me to believe there is something wrong with my current project.
However I cannot figure out what. I've tried looking at several other problems similar to mine but none of their solutions helped. Thanks in advance!
routes.js (following a request by #31piy):
var express = require("express");
var router = express.Router();
router.get("/signup",function(request,response){
response.sendFile(__dirname + "/Client/HTML/signup.html");
});
router.post("/signup",function(request,response){
});
router.get("/login",function(request,response){
response.sendFile(__dirname + "/Client/HTML/login.html");
});
You need to export the “router” from routes.js in order for it to work.
In your case add this line at the end of routes.js
module.exports = router;
That way app.use would be using an actual instance of router.
If you make a router function in different js file
It is needed to be exported so that your app.js can use it.
module.exports=router
This will help

Socket is not listening using nodejs

Thanks for help in advance. I am getting following state from my console See Server running console log. Below Snippet is my app.js code where express and node server running. If you see my socket code my console.log underneath socket connection is not showing in server logs. Socket is not listening my messages.
I have also upload my sample of code at github, here you can find that (github.com/ferozpuri/node-app) client socket code is in SocketController.js an Angular controller file.
Here is my app.js file code, As you can see console log for "Connection was made" never show. and same with socket console.
var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var engines = require('consolidate');
var routes = require('./routes');
var users = require('./routes/user');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
// view engine setup
//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'jade');
app.engine('html', engines.nunjucks);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
app.get('/', routes.index);
app.get('/users', users.list);
/// catch 404 and forwarding to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.render('error', {
message: err.message,
error: {}
});
});
io.on('connection', function (socket) {
console.log('A connection was made!');
socket.on('chat.message', function (message) {
console.log('New Message : ' + message);
});
});
module.exports = app;
I am not getting socket response from node server. PLease let me know if i not explain this properly or any thing is not here.
Server listing on port you can see this in screenshort or my project structure
Project structure & app listening port OR NPM START CODE
You have set up all handlers but you did not initialize app.
http.listen(app.get('port'), function() {
console.log('App is listening on port', app.get('port'));
});
You did not start your server. In your code, your server is created with this line:
var server = require('http').Server(app);
So, sometime after that, you need to add:
server.listen(80); // or use whatever port number you want the server on
I have resolved this issue by adding following line of code under constructing my express/after var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
#jfriend00 and #Sablor, Thanks both of you for show me right direction. my server already running on port "3000" so with port 80 its was not working. because it is conflicting with my XAMPP server. Thanks you guys for participating

Cookies undefined on node js/express (localhost)

A Newbie question I guess. I want to set and get cookies on my express site.
cookieParser is set up and seems to run. But my cookies are always undefined. So what can be wrong? Doesn't cookies work on localhost?
I can access all cookies in the console on chrome.
I have tried both httpOnly: false/true.
Here's my code:
var express = require('express'),
exphbs = require('express-handlebars'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
request = require('request'),
livereload = require('express-livereload'),
port = Number(process.env.PORT || 3000);
var log = require('./lib/log.js'));
var app = express();
livereload(app, config = {watchDir: process.cwd()});
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.use(express.static('public'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true}));
app.get('/', function(req, res) {
res
.cookie('cart', 'test', {maxAge: 900000, httpOnly: false})
.render('index');
console.log(res.cookie.cart);
});
app.listen(port, function() {
log.clear();
log.out('Express on http://localhost:' + port);
log.hr();
});
Any clues?
Maybe you should change:
console.log(res.cookie.cart);
to:
console.log(req.cookies.cart);
I just wrote a simple example that demonstrates what's going on:
var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());
app.get('/', function(req, res) {
var oldCookie = req.cookies.test;
var newCookie = (oldCookie|0) + 1;
res.cookie('test', newCookie, {maxAge: 900000});
res.status(200).json({
newCookie: newCookie,
oldCookie: oldCookie,
reqCookie: req.cookies.test,
});
});
app.listen(3000, function () {
console.log('Listening on http://localhost:3000/');
});
When you run it and go with your browser to http://localhost:3000/ you will see:
{"newCookie":1}
When you reload the page you will see:
{"newCookie":2,"oldCookie":"1","reqCookie":"1"}
Here's what's going on: In the first request even though you set the cookie in you handler before printing it it is not really set yet - it is just queued to be passed to the client in the response with an HTTP header like this one:
Set-Cookie: test=1; Max-Age=900; Path=/; Expires=Wed, 21 Sep 2016 13:03:06 GMT
In the second request you see the old value in reqCookie and the new value in newCookie - those values are different. Seeting the cookie doesn't change the one that you got in the request. I even included the reqCookie which is not stored in a variable but accessed directly from req.cookies during the res.end() invocation to demonstrate that it is not changed.

Node.js server has no response

I'm using NODE.js and Express (express-generator) to create a website. I had this working just fine yesterday afternoon, but I guess I changed something and it doesn't work now. My firewall is turned off.
I get the following in my console.
C:\website>node bin/www
Listening on 8080
Get / - - ms - -
Get / - - ms - -
Get / - - ms - -
Each of those Get / - - ms - - happens each time I try to go to 127.0.0.1:8080
Here is my bin/www file:
#!/usr/bin/env node
var debug = require('debug')('test');
var app = require('../app');
app.set('port', process.env.PORT || 8080);
var server = app.listen(app.get('port'), function() {
console.log("Listening on " + server.address().port);
debug('Express server listening on port ' + server.address().port);
});
And my app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
// production error handler
app.use(function(err, req, res, next) {
res.status(err.status || 500);
console.log(err);
});
module.exports = app;
This behavior might be the result of incorrectly defined routes. Your routes should follow this pattern:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
module.exports = router;

node js / express get posted data

How do I get posted data from my api. I am using express 3.4.4
I am doing a resful api to accept posted data using node js and express
exports.mypost = function(req, res) {
console.log(req.body);
console.log(req.body.username);
console.log(req.body.name);
var user = new UserInfo({name:"dsd", username:"dsdsds"})
user.save();
res.send("user created");
}
and I post data use
curl --data "username=dsds&name=dsd" http://localhost:3000/mypost
I can see prints
{ username: 'dsds', name: 'dsd' }
dsds
dsd
But If I use
curl --form "username=dsds&name=dsd" http://localhost:3000/mypost
I see
{}
undefined
undefined
which means I didn't catch username and name from
req.body
How do I get the data from
curl --form "username=dsds&name=dsd" http://localhost:3000/mypost
I am posting my 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 express = require('express');
var mongoose = require('mongoose');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
mongoose.connect('mongodb://localhost/data');
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
var api = require('./controllers/api.js');
app.post('/mypost', api.mypost);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Add this:
App.use(express.bodyParser());
Make sure its set before all your routes.
You can use bodyParser method to get the data from a post request
// Configure server
app.configure(function() {
app.use(express.bodyParser());
}

Categories

Resources