【发布时间】:2016-07-01 21:37:27
【问题描述】:
我正在尝试使用 Typescript 在 Angular2 中定义一个具有登录功能的简单应用程序。我已经定义了我的路由器,但在尝试访问浏览器中的 url 时出现错误。这是错误:
Cannot GET /login
我使用的网址:
http://localhost:3012/login
似乎路由器没有正确地将 URL 路由到正确的组件,我不知道为什么。这是我的 home.component.ts 实例化应用程序和路由器:
import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES, RouteConfig} from 'angular2/router';
import {LoginComponent} from './login/login.component';
import {DashboardComponent} from './dashboard/dashboard.component';
@Component({
selector: 'home',
templateUrl: '<router-outlet></router-outlet>',
directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
{path: '/login', name: 'Login', component: LoginComponent, useAsDefault: true},
{path: '/dashboard', name: 'Dashboard', component: DashboardComponent},
{path: '/*other', name: 'Other', redirectTo: ['Login']}
])
export class HomeComponent {
}
Login 和 Dashboard 组件均已正确定义,PHPStorm 未发现任何错误。
有人知道为什么会发生这种情况吗?
这是我的服务器端代码。 server.ts(NodeJS 入口点)
import express = require('express');
import path = require('path');
let port: number = process.env.PORT || 3012;
let app = express();
app.set('views', path.join('./src/Client/views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use("/node_modules", express.static(path.resolve(__dirname, '../../node_modules')));
app.use("/app", express.static(path.resolve(__dirname, '../Client/app')));
app.use("/*.html", function(req, res) {
res.render(req.params[0] + ".html");
});
app.get('/', function(req: express.Request, res: express.Response) {
res.render('index.html');
});
let server = app.listen(port, function() {
let host = server.address().address;
let port = server.address().port;
});
还有我的 index.html 文件,其中包含所有必需的 Angular2 脚本并启动 SystemJS
<html>
<head>
<title>Test</title>
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>
<script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="node_modules/angular2/bundles/router.dev.js"></script>
<script src="node_modules/angular2/bundles/http.dev.js"></script>
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('app/bootstrap')
.then(null, console.error.bind(console));
</script>
</head>
<body>
<home>Loading...</home>
</body>
</html>
还有我的文件结构:
谢谢
【问题讨论】:
-
您使用什么服务器来托管它?听起来您的服务器正试图返回目录
/login的内容。如果您使用lite-server,这将不是问题。此外,如果您切换到HashLocationStrategy,您的 URL 将是http://localhost:3012/#/login,您的服务器将正确评估。 -
你是什么版本的?
-
感谢您的快速回答。我正在使用自定义构建的 NodeJS 服务器。我不想使用 lite-server,因为我想完全控制 NodeJS 层。由于路由器之前工作正常,我看不出这是问题所在?
-
路由中的前导斜线问题?
-
我尝试删除前导斜杠无济于事。
标签: node.js typescript angular