编辑:我改变的唯一一件事就是将角度构建outDir从../dist更改为dist。现在我希望服务器发送新位置。
当我使用ng build构建我的应用程序并启动快速服务器时,一切正常。然而,在将其推送到Heroku之后,找不到dist / index.html。如果我只发送一个像res.send('testing)'
这样的字符串,但是当从dist发送index.html
时,它就会显示“Not Found”。
我一直在尝试一些方法来声明文件路径,这是当前的代码:`
//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'));
})
`
我一直在尝试只使用dist
和dist/index/html
因为它在本地服务器上工作,从指定的端口开始,它应该工作正常吗?
当我将"dist"
- 文件夹放在与server.js文件相同的目录中时,它在heroku上工作。然后我只是将文件夹名称而不是像angular-src/dist/
这样的dist文件夹的路径。
因为我更新了angular-cli,所以让outDir
走出角度项目之外更加混乱,所以我希望它能够成为“真正的”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);
});
答案 0 :(得分:2)
您的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}`);