0

I'm stuck on this problem, see if anyone can help. I have this Node.js application and when I submit a form and go to the registration part I get this error:

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:574:10)
    at ServerResponse.send (C:\projects\authentication\node_modules\express\lib\response.js:211:10)
    at ServerResponse.json (C:\projects\authentication\node_modules\express\lib\response.js:256:15)
    at C:\projects\authentication\app.js:24:7
    at Layer.handle_error (C:\projects\authentication\node_modules\express\lib\router\layer.js:71:5)
    at trim_prefix (C:\projects\authentication\node_modules\express\lib\router\index.js:315:13)
    at C:\projects\authentication\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\projects\authentication\node_modules\express\lib\router\index.js:335:12)

here is the app.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

// include routes
var routes = require('./routes/router');
app.use('/', routes);
app.use('/register', routes);

// serve static files from /public
app.use(express.static(__dirname + '/template'));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('File Not Found');
  err.status = 404;
  next(err);
});

// error handler
// define as the last app.use callback
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.json('error', {
    message: err.message,
    error: {}
  });
});

/////// JSON parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(function (req, res) {
  res.setHeader('Content-Type', 'text/plain');
  res.write('you posted:\n');
  res.end(JSON.stringify(req.body, null, 2));
});


// listen on port 3000 setting server
app.listen(3000, function () {
  console.log('Express app listening on port 3000');
});

to handle the http request I have a route.js file, which is like this:

var express = require('express');
var router = express.Router();
var path = require('path');


// GET /
router.get('/', function(req, res, next) {
   //res.setHeader('Content-type','text/plain');
   return res.sendFile(path.join(__dirname + "/../index.html"));
});

router.post('/register', function(req, res){

    //console.log(req.body);
    return res.send(req.body.email);
    /*
    if (req.body.email &&
      req.body.username &&
      req.body.password &&
      req.body.passwordConf) {
          var userData = {
            email: req.body.email,
            username: req.body.username,
            password: req.body.password,
            passwordConf: req.body.passwordConf
          };
  //use schema.create to insert data into the db
      User.create(userData, function (err, user) {
        if (err) {
          return next(err);
        } else {
          return res.redirect('/profile');
        }
      });
    }*/
});


module.exports = router;

when I try to access via get request on the root'/' it opens the html with a form, this form goes to '/register' so then I get the error, it's kind of weird how I get the html file fine via get on root but when I try to access '/register' I only get this error, already tried a lot of stuff and I can't what am I doing wrong, hope I can get some help.

HTML File

</head>
<body>
    <form action="/register" method="post">
        <div>
            <label for="email">email:</label>
            <input type="email" name="email" id="email" />
        </div>
        <div>
            <label for="username">username:</label>
            <input type="text" name="username" id="username" />
        </div>
        <div>
            <label for="password">password:</label>
            <textarea id="password" name="password"></textarea>
        </div>
        <div>
            <label for="passwordConf">password again:</label>
            <textarea name="passwordConf" id="passwordConf"></textarea>
        </div>
        <div class="button">
            <button type="submit">submit</button>
        </div>
    </form>
</body>
</html>

1 Answer 1

5

Take a look at the stack trace:

RangeError: Invalid status code: 0
    at ServerResponse.writeHead (_http_server.js:192:11)
    ...
    at C:\projects\authentication\app.js:24:7

Okay, so the error is caused on line 24 of app.js, which is this one:

  res.json('error', {
    message: err.message,
    error: {}
  });

Express is trying to interpret 'error' as a status code (because older versions of Express accepted res.json(status, obj), which has been deprecated), and because it's not something that looks like a number, internally this gets converted to the number "0", which is an invalid status code, hence the error.

I guess you meant this:

  res.json({
    message: err.message,
    error: {}
  });

EDIT: as for your other error, you need to make sure that the body-parser middleware is declared before your routes:

var bodyParser = require('body-parser');

/////// JSON parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// include routes
var routes = require('./routes/router');
app.use('/', routes);
app.use('/register', routes);

Otherwise, requests will not be passed through that middleware before they hit your route handlers.

Sign up to request clarification or add additional context in comments.

7 Comments

wow, that is a piece of code to handle errors, in fact you're right and now i'm getting the correct ERROR message, it's kind of ironic, this problem is solved but the first error still exists... now i get this message when accessing '/register' {"message":"Cannot read property 'email' of undefined","error":{}}... it looks like i am not getting the information from the post request or somethink like this.
man, this is good, you're helping but it still not perfect, if you can give me an ideia again, because now i'm getting a message with no error but the message is not correct, i'm getting only the email information. like this : {"email":"[email protected]"}
@AndreyViktorKandauroff as opposed to what? The code that your question is showing uses res.send(req.body.email).
yes sorry, i posted the HTML file, i still get only the email even trying to fetch req.body, and when i try req.body.password or username i get a blank page
So req.body only the e-mail address? As it's shown, the route for POST /register doesn't do anything apart from sending back the e-mail address, is that what you mean by "blank page"?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.