获取RangeError [ERR_HTTP_INVALID_STATUS_CODE]:无效的状态代码:在Express应用程序中未定义

时间:2018-03-10 14:22:51

标签: javascript json express pug

在我的快递应用程序中运行以下代码时出现上述错误。当我去localhost:3000 /卡。

这是在我的cards.js文件中。

const express = require('express');
const router = express.Router();
const { data } = require('../data/flashcardData.json');
const { cards } = data;

router.get('/', (req, res) => {
res.render('card', {
prompt: cards[0].question,
hint: cards[0].hint
 });
});

module.exports = router;

这是我的app.js文件中的代码。

const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

 app.set('view engine', 'pug');

 const mainRoutes = require('./routes');
 const cardRoutes = require('./routes/cards');

 app.use(mainRoutes);
 app.use('/cards', cardRoutes);

 app.use((req, res, next) => {
 const err = new Error('Not Found');
 err.status = 404;
 next(err);
 });

app.use((err, req, res, next) => {
res.locals.error = err;
res.status(err.status);
res.render('error');
});

 app.listen(3000, () => {
 console.log('The application is running on localhost:3000!');
 });

任何帮助将不胜感激。基本上,我正在尝试将json文件合并到快速应用程序中,并且它出现了这个错误。

1 个答案:

答案 0 :(得分:1)

如果错误不包含属性状态,请在错误处理程序中间件中设置默认状态。

const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.set('view engine', 'pug');

const mainRoutes = require('./routes');
const cardRoutes = require('./routes/cards');

app.use(mainRoutes);
app.use('/cards', cardRoutes);

app.use((req, res, next) => {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.use((err, req, res, next) => {
  res.locals.error = err;
  const status = err.status || 500;
  res.status(status);
  res.render('error');
});

app.listen(3000, () => {
  console.log('The application is running on localhost:3000!');
});