Node.js应用出现Cannot GET /及404资源加载失败错误求助
排查Node.js Express应用的404错误:Cannot GET /
运行Node.js应用时,浏览器和控制台出现如下错误:Cannot GET / 和 Failed to load resource: the server responded with a status of 404 (Not Found)

相关代码文件
server.js
const express = require('express') const app = express() const logger = require('morgan') const cors = require('cors') const bodyParser = require('body-parser') const config = require('./api/utils/config') const db = require('./api/utils/db') const v1Routes = require('./routes/V1routes') logger.token('date', () => { return new Date().toLocaleString("en-US", { timeZone: "America/New_York" }) }) app.use(logger('[:date[]] :remote-addr ":method :url HTTP/:http-version" :status ')) app.use(bodyParser.urlencoded({ extended: true, limit: '200mb' })) app.use(bodyParser.json({ limit: '200mb' })) app.use(express.json()) app.use(express.urlencoded({ extended: true })) app.use(cors()) app.use((req, res, next) => { res.setHeader('Access-Control-Allow-Origin', '*') res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE') res.setHeader('Access-Control-Allow-Headers', '*') res.setHeader('Access-Control-Allow-Credentials', true) next() }) app.use('/assets', express.static('assets')) app.use('/static', express.static('static')) app.use('/api/v1', v1Routes) db.getConnection() .then(() => { app.listen(config.port, async () => { console.log(`Server Started at http://${config.host}:${config.port}`) }) }) .catch((error) => { console.log(error) }) module.exports = app;
.env
APP_NAME=DTLive APP_ENV=local APP_KEY=base64:GHlKvYv+hmpj0KR+73qH5APmQmZcjVARI0ABBCMcFIM= APP_DEBUG=true APP_URL=http://localhost/admin/public/admin/login LOG_CHANNEL=stack LOG_DEPRECATIONS_CHANNEL=null LOG_LEVEL=debug DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=dt_live DB_USERNAME=root DB_PASSWORD= BROADCAST_DRIVER=log CACHE_DRIVER=file FILESYSTEM_DRIVER=local QUEUE_CONNECTION=sync SESSION_DRIVER=file SESSION_LIFETIME=120 MEMCACHED_HOST=127.0.0.1 REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379 MAIL_MAILER=smtp MAIL_HOST=mailhog MAIL_PORT=1025 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null MAIL_FROM_ADDRESS=null MAIL_FROM_NAME="${APP_NAME}" AWS_ACCESS_KEY_ID= AWS_SECRET_ACCESS_KEY= AWS_DEFAULT_REGION=us-east-1 AWS_BUCKET= AWS_USE_PATH_STYLE_ENDPOINT=false PUSHER_APP_ID= PUSHER_APP_KEY= PUSHER_APP_SECRET= PUSHER_APP_CLUSTER=mt1 MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}" MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}" JWT_SECRET= IMAGE_PATH=http://localhost/admin/public/images/ API_URL=http://localhost/admin/api/
config.js
module.exports = (function () { let data = { IMAGE_BASE_PATH: "http://localhost/admin/public/images/", BASE_PATH: "http://localhost/admin/public/", USER_BASE_PATH: "C:/xampp/htdocs/admin/public/images/", JWTSecretKey: "", default_auth_token: "jQfq4I2q6lv", refresh_token: "", host: "localhost", port: 8080, androidAppVerision: "1.0.0", iosAppVerision: "1.0.0", mailerEmail: "", mailerPassword: "@", awsAccesskey: "", awsSecretkey: "", s3bucketName: "", s3uploadURL: "", buildingRadius: 50, paginationCount: 5, colorLogoLink: '', notificaionCount: 10, landlord_flag: 1, property_manager_flag: 2, attorney_flag: 3, process_server_flag: 4, admin_flag: 5, distanceRadius: 10, admin_user_type_for_chat_user: 5, budget_sms_username: "", budget_sms_user_id: "", budget_sms_handle: "", timeRegex: /^(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)?([0-5]?\d)$/, dateRegex: /^(19|20|21|22)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$/, language: [{ name: "en", value: "English" }, { name: "tr", value: "Turkish" }, { "name": "fa", "value": "Farsi" }, { "name": "ar", "value": "Arabic" }], auto_detect_code: "jQfq4I2q6lv", distanceMatrixAPI: "", adminPanelLink: '' } data.host = 'localhost' data.db = { host: "localhost", user: "root", password: "", database: "dt_live" } data.forgotPasswordLinkPrefix = `` data.reset_password_link = `` data.privacy_policy_url = `` data.terms_and_conditions_url = `` data.paymentLink = `` data.iyzicoKey = `` data.iyzicoSecretKey = `` data.iyzicoURI = `` return data; })();
排查与解决方法
根路由未定义:当前server.js仅配置了
/api/v1、/assets、/static三类路由,没有处理根路径/的请求,访问http://localhost:8080自然返回404。添加根路由处理即可:// 在app.use('/api/v1', v1Routes)前后均可添加 app.get('/', (req, res) => { res.send('服务器运行正常!'); // 若需返回前端页面,可改为: // const path = require('path'); // res.sendFile(path.join(__dirname, 'path/to/your/index.html')); });API子路由检查:访问
http://localhost:8080/api/v1时,如果V1routes.js中未定义该路径的处理逻辑,也会返回404。需确保V1routes.js中有根路由配置:const express = require('express'); const router = express.Router(); router.get('/', (req, res) => { res.json({ message: 'API v1 服务正常' }); }); // 其他业务路由... module.exports = router;静态资源路径验证:确认项目根目录下存在
assets和static文件夹,否则访问/assets或/static开头的路径也会触发404。若文件夹不存在,需创建对应目录或调整express.static的路径参数。地址一致性检查:.env中的
API_URL为http://localhost/admin/api/,但Express服务运行在8080端口,前端请求API时需使用正确地址http://localhost:8080/api/v1/xxx,避免因路径不匹配导致404。
内容的提问来源于stack exchange,提问作者Shahriya Islam
相关产品推荐
相关产品推荐

