ito2307ht ito2307ht - 1 month ago 15
Jade Question

How can i fix this error in expressjs

i'm using expressjs with jade. I'm trying to do a factorial with an input, but i can't display the answer for example if i input 5 the result is 120, but display a big error. How can i make this?
Please can you help me?
error



routes/index.js

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

/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index.jade', { title: 'Express' });
});


router.get('/factorial', function(req, res, next) {
res.render('factorial.jade', { title: 'Factorial' });
});



module.exports = router;

views/factorial

extends layout

block content
h1= title
p Welcome to #{title}
p Ingrese un numero
form(method="POST", action="/factorial", name="myForm",onsubmit='return validateForm()')
input(type='number', name='numero')
input(type='submit', value='Enviar')

<strong>archive app.js</strong>

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
//agregado
var bodyParser = require('body-parser');
var engine = require('ejs-mate');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// instruct the app to use the `bodyParser()` middleware for all routes
app.use(bodyParser());

// view engine setup
app.engine('ejs', engine);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');


app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());

app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'bower_components')));

app.use('/', routes);
app.use('/users', users);

app.post('/factorial', function(req, res) {
var num=req.body.numero;
dd(num);
for(var i=1;i<=num;i++)
i=i*num;
res.send('/factorial'+i);
});

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});


module.exports = app;




Answer

try this:

var express = require("express")
var app = express()

function factorial(num) {
  if (num < 0)
    return "INVALID"
  if (num == 1 || num == 0)
    return 1
  else return num * factorial(num - 1)
}

app.get("/factorial/:num", function (req, res) {
  var num = req.params.num;  
  res.status(200).send(""+factorial(num))
})

app.listen(3000)

point your browser to http://localhost:300/factorial/4 for example.

Comments