我问这个问题是因为我不确定从前端还是后端是解决我的问题的方法。
基本上,我有一个问题,当从一开始以不同的方式重新加载页面时"/"
,出现错误"not found 404"
,我看到了一些可能的解决方案,例如包含“哈希”,但是对于SEO问题,我无法做到。我还看到有解决此问题的配置,但是这些配置在apache服务器或ISS中。
ng serve
当与结合使用angular-cli时,我的应用程序运行良好,但是当我运行
ng build --prod --base-href=./ and --deploy-url=./
重新加载页面时,路线不起作用。
例如:
http://localhost/my_folder_compilated/programa/detalle-programa/5cf7d27faa8e180017211754 --> 404 not found!
我需要将其部署在Heroku服务器上,或者在不存在的情况下将其部署在nodejs上。
我怎么解决这个问题?
// this is the route that I have in my app.routing.ts
{path: 'programa/detalle-programa/:programaId', component:
DetalleProgramaComponent},
{path: '**', component: NotFoundComponent}
注意
我认为解决方案在后端。我正在使用nodejs(快速),但无法修复。
更新资料
我正在使用此代码,并且在我的路线上效果很好,
const distDirectory = path.join(__dirname, 'public');
app.get('*', function (req, res, next) {
const file_path = path.join(distDirectory, req.url.split('?').shift());
console.log(file_path)
if (fs.existsSync(file_path)) next();
else res.sendFile(path.join(distDirectory, 'index.html'));
});
app.use(express.static(distDirectory));
除了这一点:
localhost/programa/detalle-programa/5cf7d27faa8e180017211754
在控制台中,这是我收到的路由:
...public\programa\detalle-programa\runtime.366eb317d0165de30d51.js
显然它不存在,并且在我的文件中标记为错误
更新2:
我的服务器heroku上的文件夹是:
public --> here my files, and the index.html
而我的index.html是:
<head>
<meta charset="utf-8">
<title>title</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="styles.51e30e538d2560c1a9e9.css">
</head>
<body>
<app-root ></app-root>
<script type="text/javascript" src="/runtime.a5dd35324ddfd942bef1.js">
</script>
<script type="text/javascript" src="/polyfills.3eb7881d3a00da6c675e.js">
</script>
<script type="text/javascript" src="/scripts.dd86f002a5aef1b13f0f.js">
</script>
<script type="text/javascript" src="/main.23ac360bc829b49bc07d.js">
</script>
</body>
</html>
我发生的问题是,我收到的所有请求都返回了index.html文件,这就是为什么无法兑现我的服务承诺的原因。
在您的expressindex.js
文件中使用以下设置,将设置distDirectory
为您的dist
目录。
const path = require('path');
const express = require('express');
const fs = require('fs');
const app = express();
const distDirectory = path.join(__dirname, 'dist');
app.get('*', function (req, res, next) {
const file_path = path.join(distDirectory, req.url.split('?').shift());
if (fs.existsSync(file_path)) next();
else res.sendFile(path.join(distDirectory, 'index.html'));
});
app.use(express.static(distDirectory));
app.listen(80, function () {
console.log('listening');
});
更新:使用以上代码,您的路由有效,但是JavaScript和CSS文件却得到404。原因是:
// Never use a leading dot in base-href
ng build --prod --base-href=./
^^
有效的基本网址的几个示例:
website url: http://localhost/my_folder_compilated/
base url: /my_folder_compilated/
website url: http://localhost:4200/public/
base url: /public/
注意:您不需要设置--deploy-url=./
,base-url
只能使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句