使用Nodemon时Express服务器无法启动或连接的问题求助
问题:Express项目启动后无服务器地址提示,无法访问localhost
我用Express、Node和Nodemon搭建了新项目,完成基础配置后执行npm start,终端只显示启动基础信息,没有服务器运行地址的提示,访问localhost也连不上,不知道问题在哪。
package.json 文件内容
{ "name": "resturant-picker", "version": "1.0.0", "description": "Resturant picker app for Alchs", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "nodemon server.js" }, "repository": { "type": "git", "url": "git+https://github.com/connordensmore/resturant-picker.git" }, "keywords": [ "crud", "mongodb" ], "author": "Connor", "license": "ISC", "bugs": { "url": "https://github.com/connordensmore/resturant-picker/issues" }, "homepage": "https://github.com/connordensmore/resturant-picker#readme", "dependencies": { "axios": "^0.27.2", "body-parser": "^1.20.0", "dotenv": "^16.0.2", "ejs": "^3.1.8", "express": "^4.18.1", "mongoose": "^6.5.5", "morgan": "^1.10.0", "node": "^18.8.0", "nodemon": "^2.0.19" } }
server.js 文件内容
const express = require("express"); const app = express(); const PORT = process.env.PORT || 3000; app.get("/", (req, res) => { res.send("Crud App"); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); }); });
执行npm start后的终端响应
mopdog@Connors-MacBook-Pro resturant-picker % npm start > resturant-picker@1.0.0 start > nodemon server.js [nodemon] 2.0.19 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] starting `node server.js` [nodemon] clean exit - waiting for changes before restart
解决方案
问题核心是**app.listen()被错误放在了app.get("/")的路由回调内部**:
- Express只有在访问根路径
/时才会执行该回调里的代码,但服务器没启动的话根本无法访问/,直接陷入逻辑死循环。 - 因为服务器始终没启动,Node.js执行完顶部代码后就直接退出,所以nodemon提示
clean exit,等待文件变更后重启。
修复方法很简单,把app.listen()移出路由回调,放在文件最外层:
const express = require("express"); const app = express(); const PORT = process.env.PORT || 3000; app.get("/", (req, res) => { res.send("Crud App"); }); // 将服务器启动代码移到路由定义之外 app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
修改后重新执行npm start,就能看到服务器启动的地址提示,访问http://localhost:3000也能正常返回内容。
内容的提问来源于stack exchange,提问作者Connor Densmore
相关产品推荐
相关产品推荐

