javascript 获取RangeError [ERR_HTTP_INVALID_STATUS_CODE]:无效状态代码:在express应用中未定义

jdzmm42g  于 2023-05-05  发布在  Java
关注(0)|答案(2)|浏览(121)

我在我的express应用程序中运行以下代码时出现上述错误。当我去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文件合并到Express应用程序中,它出现了这个错误。

rryofs0p

rryofs0p1#

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

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!');
});
c7rzv4ha

c7rzv4ha2#

在我的情况下,发生这种情况是因为我没有在我的请求中提供授权:)

相关问题