带有节点路由问题的angular2
angular2 with node routes issue
我目前正在使用 angular2,出于部署目的,我必须使用节点作为我的服务器。我被困在路线中
成功场景:
如果我使用 routerLink 导航到页面,它工作正常节点很好地为他们服务
路线是:http://localhost:8080/sign-in --- 工作正常
失败场景:
如果我在地址栏中手动输入与上面相同的地址,则无法加载页面
即它一直在说 index.html 和其他路由不工作的应用程序加载
index.js
const express = require('express');
const app = express();
var path = require("path");
app.use(express.static(__dirname + '/dist'));
app.get('/[^\.]+$', function(req, res) {
console.log(__dirname+'/src/index.html')
res.sendFile(path.join(__dirname+'/src/index.html'))
});
app.listen(process.env.PORT || 8080);
问题出在无法提供页面的节点服务器上,但我希望路由即使在地址栏中也能正常工作任何帮助将不胜感激
该应用程序适用于 生产模式 angular 4
尝试使用 HashLocationStrategy 作为 LocationStrategy:
import { HashLocationStrategy, LocationStrategy } from '@angular/common';
@NgModule({
// ...
providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
// ...
})
export class AppModule {}
在您的 angular 项目中:
不要忘记使用 ng build 来构建您的项目。之后,您将看到一个新目录:dist
此目录包含您的 angular 项目。
在您的节点项目中:
您必须发送 angular 项目中的所有路由:
// Send all other requests to the Angular app
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'yourprojectangular/dist/index.html'));
});
我目前正在使用 angular2,出于部署目的,我必须使用节点作为我的服务器。我被困在路线中
成功场景:
如果我使用 routerLink 导航到页面,它工作正常节点很好地为他们服务
路线是:http://localhost:8080/sign-in --- 工作正常
失败场景: 如果我在地址栏中手动输入与上面相同的地址,则无法加载页面
即它一直在说 index.html 和其他路由不工作的应用程序加载
index.js
const express = require('express');
const app = express();
var path = require("path");
app.use(express.static(__dirname + '/dist'));
app.get('/[^\.]+$', function(req, res) {
console.log(__dirname+'/src/index.html')
res.sendFile(path.join(__dirname+'/src/index.html'))
});
app.listen(process.env.PORT || 8080);
问题出在无法提供页面的节点服务器上,但我希望路由即使在地址栏中也能正常工作任何帮助将不胜感激 该应用程序适用于 生产模式 angular 4
尝试使用 HashLocationStrategy 作为 LocationStrategy:
import { HashLocationStrategy, LocationStrategy } from '@angular/common';
@NgModule({
// ...
providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
// ...
})
export class AppModule {}
在您的 angular 项目中:
不要忘记使用 ng build 来构建您的项目。之后,您将看到一个新目录:dist 此目录包含您的 angular 项目。
在您的节点项目中:
您必须发送 angular 项目中的所有路由:
// Send all other requests to the Angular app
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'yourprojectangular/dist/index.html'));
});