为何无法在浏览器中打开localhost:4500?附终端报错及代码
问题排查与修复
你的代码存在几个关键错误,导致无法正常访问localhost:4500:
1. Express路由方法调用错误
你错误地将app.get当作变量赋值,正确写法是调用app.get()方法注册路由,原写法会覆盖Express内置的get方法,导致路由无法被正确处理,这是终端报错的核心原因。
错误代码:
app.get = ("/", function (req, res) { res.sendFile(dirname + "/index.html"); });
修复后:
app.get("/", function (req, res) { res.sendFile(path.join(__dirname, "/index.html")); });
2. __dirname未正确使用且缺少path模块
__dirname是Node.js内置变量(注意是双下划线),直接拼接路径易出现跨平台问题,建议引入path模块用path.join()处理路径,需要在代码顶部添加:
const path = require('path');
3. 监听端口的规范问题
app.listen("4500")中端口用字符串虽能被Node.js自动转换,但更规范的写法是使用数字类型端口号,同时添加回调函数可直观查看服务器启动状态:
app.listen(4500, () => { console.log("服务器运行在http://localhost:4500"); });
完整修复后的代码
const mysql = require("mysql"); const path = require('path'); const express = require("express"); const app = express(); const connection = mysql.createConnection({ host: "localhost", user: "root", password: "Ahd12332199", database: "nodejs", }); // 连接数据库 connection.connect(function (error) { if (error) throw error; else console.log("数据库连接成功!"); }); app.get("/", function (req, res) { res.sendFile(path.join(__dirname, "/index.html")); }); app.listen(4500, () => { console.log("服务器已启动,访问地址:http://localhost:4500"); });
修复后重启服务器,即可正常访问localhost:4500。
内容的提问来源于stack exchange,提问作者THE GAME
相关产品推荐
相关产品推荐

