1

我是 Node.js 的新手,我尝试使用 node.js 开发一个简单的电影 api 应用程序,并使用 express-generator 创建了应用程序。我得到了这个错误,我无法处理它。

首先,我用谷歌搜索,发现我检查了 github 和 stackoverflow,但我无法解决我的问题。

首先是这里的错误信息:

TypeError [ERR_INVALID_ARG_TYPE]:“路径”参数必须是字符串类型。在新视图 (/Users/tugrul/Projects/Learning Projects/movie-api/node_modules/express/lib) 的 extname (path.js:1231:5) 处接收到类型对象/view.js:56:14) 在 Function.render (/Users/tugrul/Projects/Learning Projects/movie-api/node_modules/express/lib/application.js:570:12) 在 ServerResponse.render (/Users/ tugrul/Projects/Learning Projects/movie-api/node_modules/express/lib/response.js:1008:7) 在 /Users/tugrul/Projects/Learning Projects/movie-api/app.js:45:7 层。 handle_error (/Users/tugrul/Projects/Learning Projects/movie-api/node_modules/express/lib/router/layer.js:71:

这是我的 package.json 文件:

{
  "name": "movie-api",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "nodemon ./bin/www"
  },
  "dependencies": {
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "jade": "~1.11.0",
    "mongoose": "^5.9.10",
    "morgan": "~1.9.1"
  }
}

这是我的 app.js 文件:

const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');

const indexRouter = require('./routes/index');
const movieRouter = require('./routes/movie');
const directorRouter = require('./routes/director');


const app = express();

//mongodb connection

const db = require('./helper/db')();

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

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/api/movies', movieRouter);
app.use('api/directors', directorRouter);

// catch 404 and forward to error handler
app.use((req, res, next) => {
  next(createError(404));
});

// error handler
app.use((err, req, res, next) => {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render({error:{message:err.message, code: err.code}});
});

module.exports = app;

这是我的导演路由器文件:

const express = require('express');
const router = express.Router();
//Models

const Director = require('../models/Director');

    // Get All Movies
    router.get('/', (req, res, next) =>{
      res.json({message: 'Director APIs'});
    });


    module.exports = router;

这是我的电影路由器文件:

const express = require('express');
const router = express.Router();
//Models

const Movie = require('../models/Movie');

// Get All Movies
router.get('/', (req, res) =>{
  const promise = Movie.find({ });
  promise.then((data)=>{
    res.json(data);
  }).catch((err)=>{
    res.json(err)
  });
});

//Top 10 List
router.get('/top10', (req, res) =>{
  const promise = Movie.find({ }).limit(10).sort({ imdb_score: -1});
  promise.then((data)=>{
    res.json(data);
  }).catch((err)=>{
    res.json(err)
  });
});

//Add new movie
router.post('/add-movie',(req,res,next)=>{
  //const {title,imdb_score,category,country,year} = req.body;
  const movie = new Movie(req.body);

  const promise = movie.save();

  promise.then((data)=>{
    res.json(data);
  }).catch((err)=>{
    res.json(err);
  });

});


// Get Movie From ID
router.get('/:movie_id',(req,res,next)=>{
  const promise = Movie.findById((req.params.movie_id));
  promise.then((movie)=>{

    if(!movie){
      console.log(movie);
      next({message : 'This movie can not found!', code:404});
    }else{
      res.json(movie);
    }
  }).catch((err)=>{
    res.json(err);
  });

});


//Update Movie
router.put('/:movie_id',(req,res,next)=>{
  const promise = Movie.findByIdAndUpdate(
      req.params.movie_id,
      req.body,
      {
        new: true
      });
  promise.then((movie)=>{

    if(!movie){
      console.log(movie);
      next({message : 'This movie can not found!', code:404});
    }else{
      res.json(movie);
    }
  }).catch((err)=>{
    res.json(err);
  });

});

//Delete movie
router.delete('/:movie_id',(req,res,next)=>{
  const promise = Movie.findByIdAndRemove(
      req.params.movie_id,
      req.body);
  promise.then((movie)=>{

    if(!movie){
      console.log(movie);
      next({message : 'This movie can not found!', code:404});
    }else{
      res.json({status: 1});
    }
  }).catch((err)=>{
    res.json(err);
  });

});

// get movies between two years
router.get('/between/:start_year/:end_year',(req,res,next)=>{
  const {start_year,end_year} = req.params;
  const promise = Movie.find(
      {
        // gte = ">=", lte = "<="
        year: { "$gte": parseInt(start_year), "$lte": parseInt(end_year)}
      }
  );
  promise.then((movie)=>{

    if(!movie){
      console.log(movie);
      next({message : 'This movie can not found!', code:404});
    }else{
      res.json(movie);
    }
  }).catch((err)=>{
    res.json(err);
  });

});


module.exports = router;

当我尝试访问http://localhost:3000/api/directors时出现此错误。为什么?我该如何处理?

请问你能帮帮我吗?

4

1 回答 1

1

问题是以下行:

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

根据文档render期望第一个参数是要呈现的 html 页面的路径。假设error在您的视图目录中调用了一个文件,将其更改为

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

应该解决问题。

关于评论中的第二个问题:

这里的问题是你的中间件:

// catch 404 and forward to error handler
app.use((req, res, next) => {
  next(createError(404));
});

基本上每个请求都会导致错误,因为您设置了一个普通的中间件,该中间件也将在成功请求时执行。因此,您可能只需删除此中间件,因为您已经设置了错误处理程序。

于 2020-04-28T15:30:31.177 回答