Express项目遇Nodemon崩溃及GET请求报错问题求助
Express项目排查:404错误与Nodemon崩溃问题
我编写了一个Express项目,包含app.js、route.js、controller.js三个文件,原本期望访问http://localhost:3000/api/products能正常获取响应,但先遇到了GET请求找不到的404错误,现在又出现Nodemon crashed and waiting for file to be changed的崩溃提示,请求协助排查问题。
app.js代码
const express = require("express"); const app = express(); const PORT = process.env.PORT || 3000; const products_routes = require("./routes/products"); app.get("/", (req, res) => { res.send("Hello this is my API"); }) app.use("/api/products", products_routes); const start = async() => { try { app.listen(PORT, () => { console.log(`${PORT} Yes I am connected`); }); } catch (error) { console.log(error); } } start();
route.js代码
const express = require("express"); const router = express.Router(); const { getAllProducts, getAllProductsTesting } = require("../controllers/products"); router.route("/").get(getAllProducts); router.route("/testing").get(getAllProductsTesting);
controller.js代码
const getAllProducts = async (req, res) => { res.status(200).json({ msg: "I am getAllProducts" }); } const getAllProductsTesting = async (req, res) => { res.status(200).json({ msg: "I am getAllProductsTesting" }); } module.exports = { getAllProducts, getAllProductsTesting };
排查步骤
一、修复Nodemon崩溃问题
- 确认依赖安装完整:执行
npm install,确保express、nodemon等依赖都正确安装 - 修正文件路径与命名:
- 新建
routes文件夹,把当前的route.js重命名为products.js并放入该文件夹 - 新建
controllers文件夹,把当前的controller.js重命名为products.js并放入该文件夹 - 代码里的引入路径
./routes/products和../controllers/products对应上述文件位置,路径不匹配会导致模块加载失败,直接引发Nodemon崩溃
- 新建
- 检查端口占用:3000端口可能被其他程序占用,执行对应命令排查:
- Mac/Linux:
lsof -i :3000,找到进程后用kill -9 <进程ID>杀掉 - Windows:
netstat -ano | findstr :3000,找到进程ID后用taskkill /F /PID <进程ID>杀掉 - 或者直接修改app.js里的PORT值为其他未被占用的端口,比如3001
- Mac/Linux:
二、解决404请求错误
- 确认路由挂载生效:完成上述文件结构调整后,app.js里的
app.use("/api/products", products_routes)会正确挂载路由,此时访问http://localhost:3000/api/products会触发getAllProducts方法返回响应 - 注意访问协议:代码里没有配置HTTPS证书,所以不能用
https://访问,必须用http://localhost:3000/api/products
内容的提问来源于stack exchange,提问作者Pratik Bhowmik
相关产品推荐
相关产品推荐

