Angular项目通过Git部署Heroku成功后访问提示'Not Found'如何解决
问题排查与解决方法
最核心的常见错误:server.js路径写法不规范
你当前server.js中path.join的用法错误,自行用加号拼接路径可能出现路径识别失败,直接返回404。请将server.js替换为以下规范写法:
const express = require('express'); const path = require('path'); const app = express(); // 用path.join自动适配不同系统的路径分隔符,避免拼接错误 app.use(express.static(path.join(__dirname, 'dist', 'application-reminder'))); app.get('/*', function(req,res) { // path.join接收多段路径作为参数,不要自行用加号拼接 res.sendFile(path.join(__dirname, 'dist', 'application-reminder', 'index.html')); }); app.listen(process.env.PORT || 8080);
补充:package.json中
heroku-postbuild脚本的--prod参数已废弃,可改为ng build --configuration production消除警告,不影响现有构建结果。
其他需要确认的排查点
- 确认
server.js文件放在项目根目录,和package.json处于同一级 - 打开项目根目录的
angular.json文件,找到如下配置节点,确认outputPath的值为dist/application-reminder:"projects": { "application-reminder": { "architect": { "build": { "options": { "outputPath": "dist/application-reminder" } } } } } - 本地验证:本地执行
ng build --configuration production命令,检查生成的dist目录下是否存在application-reminder文件夹,文件夹内是否有index.html文件 - 若仍未解决,可在server.js中加入日志代码,部署后通过
heroku logs --tail查看运行日志确认路径是否正确:const fs = require('fs'); const targetPath = path.join(__dirname, 'dist', 'application-reminder'); console.log('静态资源路径:', targetPath); console.log('路径是否存在:', fs.existsSync(targetPath)); console.log('index.html是否存在:', fs.existsSync(path.join(targetPath, 'index.html')));
内容的提问来源于stack exchange,提问作者Randika Geekiyanage
相关产品推荐
相关产品推荐

