我有一个必须从中获取数据的表格。我正在使用ejs模板。 我的“ /”路由呈现“主”视图,并且我有一个中间件来处理来自表单的数据,但是它返回错误“ RangeError:超出最大调用堆栈大小”
我的Express代码:
const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
const validator = require('validator.js');
app.set('view engine','ejs');
const urlEncodedParser = app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname + '/public')));
app.get('/',(req,res)=>{
res.render('main');
});
app.post('/register', urlEncodedParser, (req,res)=>{
console.log(req.body);
});
app.listen(3000);
我的表单:
<form action="/register" method="POST">
<input type="text" name='name' class="form-control">
<input type="text" name='surname' class="form-control">
<input type="number" name='age' class="form-control">
<input type="email" name='email' class="form-control">
<input type="password" name='password' class="form-control">
<input type="password" name='confirm' class="form-control">
<input type="submit" name="submit" class="btn btn-block btn-success" value="OKAY">
</form>
我得到的完整错误:
RangeError: Maximum call stack size exceeded
at next (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\index.js:202:7)
at Layer.handle [as handle_request] (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\layer.js:97:5)
at trim_prefix (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\index.js:317:13)
at C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\index.js:335:12)
at next (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\index.js:275:10)
at jsonParser (C:\xampp\htdocs\express+mongo\node_modules\body-parser\lib\types\json.js:101:7)
at Layer.handle [as handle_request] (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\index.js:317:13)
at C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\index.js:284:7
答案 0 :(得分:3)
问题的原因是您将应用程序作为中间件传递给请求处理程序。具体在这里:
const urlEncodedParser = app.use(bodyParser.urlencoded({extended:false}));
app.post('/register', urlEncodedParser, (req,res)=>{
console.log(req.body);
});
urlEncodedParser
只是对您的应用程序的另一个引用。因此,您陷入无限循环,其中路由调用urlEncodedParser
向下流到您的路由,路由依次调用urlEncodedParser
,依此类推,直到弹出堆栈。
答案 1 :(得分:1)
urlEncodedParser
引起了问题,它不应该出现在中间件中:
const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
const validator = require('validator.js');
app.set('view engine','ejs');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname + '/public')));
app.get('/',(req,res)=>{
res.render('main');
});
app.post('/register', (req,res)=>{
console.log(req.body);
});
app.listen(3000);