You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何无法在浏览器中打开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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 18:09:19