express -e 文件名 (路由报错404处理)

Not Found
404
NotFoundError: Not Found
    at D:\__easyHelper__\node.js\记账本\noteaccounts\app.js:27:8
    at Layer.handle [as handle_request] (D:\__easyHelper__\node.js\记账本\noteaccounts\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (D:\__easyHelper__\node.js\记账本\noteaccounts\node_modules\express\lib\router\index.js:317:13)
    at D:\__easyHelper__\node.js\记账本\noteaccounts\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (D:\__easyHelper__\node.js\记账本\noteaccounts\node_modules\express\lib\router\index.js:335:12)
    at next (D:\__easyHelper__\node.js\记账本\noteaccounts\node_modules\express\lib\router\index.js:275:10)
    at D:\__easyHelper__\node.js\记账本\noteaccounts\node_modules\express\lib\router\index.js:635:15
    at next (D:\__easyHelper__\node.js\记账本\noteaccounts\node_modules\express\lib\router\index.js:260:14)
    at Function.handle (D:\__easyHelper__\node.js\记账本\noteaccounts\node_modules\express\lib\router\index.js:174:3)
    at router (D:\__easyHelper__\node.js\记账本\noteaccounts\node_modules\express\lib\router\index.js:47:12)

明明app.js 27行并没有错误,但是报错了

处理方式:

`app.use` 是 Express.js 中用于注册中间件的方法,你提供的代码片段中使用了
 `app.use` 来注册一个中间件函数。这个中间件函数的作用是将请求进一步传递给
下一个中间件函数,但同时也会调用 `next` 方法传递一个 404 错误对象作为参数。

在代码中看不到 `createError` 的定义,所以这段代码运行时会产生错误。
`createError` 是一个第三方库(通常是 `http-errors` 模块)中的函数,
用于创建 HTTP 错误对象。你需要先安装该模块,然后导入它,才能正确使用 `createError`。

你可以通过执行以下步骤来解决这个问题:

1. 打开终端并确保你的项目目录下存在 `package.json` 文件。

2. 在终端中使用以下命令安装 `http-errors` 模块:

  
   npm install http-errors
   

3. 在你的代码文件的开头添加如下语句来导入 `createError` 函数:

  
   const createError = require('http-errors');
   

   请确保这行代码在调用 `app.use` 的位置之前。

4. 然后你可以使用 `createError` 来创建 404 错误对象,并将其传递给 `next` 方法:

 
   app.use(function(req, res, next) {
     next(createError(404));
   });
 

这样,当你的应用程序收到一个请求时,它将执行该中间件函数,并将一个 404 错误对象
传递给下一个中间件函数来处理这个错误。记得根据你的具体需求,在后续中间件或错误处
理中间件中对这个错误进行适当的处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值