sendFile()在推送到heroku时不发送ng build dist / index.html文件

编辑:我改变,使其无法正常工作的唯一变化是从../dist到dist的angular度生成outDir。 现在我想让服务器发送新的位置。

当我使用ng build构build我的应用程序并启动express服务器时,一切正常。 然后把它推到Heroku dist / index.html找不到。 它工作,如果我只是发送一个string像: res.send('testing)'但从res.send('testing)'发送index.html它只是说“未find”。

我一直在尝试一些方法来声明文件path,这是当前的代码:`

 //Set static folder app.use(express.static(path.join(__dirname, 'angular-src/dist'))); //Index route app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'angular-src/dist/', 'index.html')); }) 

`

我也一直只用distdist/index/html尝试

由于它在本地服务器上工作,从指定的端口开始,它应该正常工作?

当我在与server.js文件相同的目录中有"dist"文件夹时,它在heroku上工作。 然后,我只是把文件夹名称,而不是dist文件夹的path,如angular-src/dist/

由于我更新了angular度cli,所以使outDir超出了angular度项目的范围,所以我希望它走向“真正的” dist

编辑:添加我的整个server.js文件下面

 const path = require('path'); const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const mongoose = require('mongoose'); const config = require('./config/database'); const compression = require('compression'); //Connect to database mongoose.connect(config.database); //If connected to the database mongoose.connection.on('connected', () => { console.log("connected to db: " + config.database); }); //IF there's problems with the connection to the database mongoose.connection.on('error', (err) => { console.log("Db error: " + err); }); const app = express(); const users = require('./routes/users'); const friends = require('./routes/friends'); const port = process.env.PORT || 8080; //Cors middleware app.use(cors()); app.use(compression); //Set static folder app.use(express.static(__dirname +'/dist')); //Body parser middleware app.use(bodyParser.json()); app.use('/users', users); app.use('/friends', friends); //Index route app.get('/*', (req, res) => { res.sendFile(path.join(__dirname + '/dist/index.html')); }) //Start server app.listen(port, () => { console.log("server started on port: "+ port); }); 

你的server.js必须如下所示:

  const compression = require('compression'); const path = require('path'); const express = require('express'); const app = express(); const port = process.env.PORT || 8080; // Gzip app.use(compression()); // Run the app by serving the static files in the dist directory app.use(express.static(__dirname + '/dist')); // Start the app by listening on the default Heroku port app.listen(port); // For all GET requests, send back index.html so that PathLocationStrategy can be used app.get('/*', function(req, res) { res.sendFile(path.join(__dirname + '/dist/index.html')); }); console.log(`Server listening on ${port}`);