我有一个类似于 'localhost:3000/verify/a5d5sd' 的 URL,我已将其发送到用户的电子邮件,单击此链接后,我在中使用参数 (a5d5sd)用于检查服务器和数据库(MongoDB)中的某些内容并返回对象响应的链接,现在当单击该链接或在新选项卡上打开该链接时,我只能看到来自服务器的响应,但看不到来 self 的 HTML 的响应Angular 2 组件。
在我的 Angular 2 路由配置模块中,我配置了如下路由
{
path: 'verify/:id',
component: MyComponent
},
在该组件的 ngOnInit 上,我调用一个服务方法,该方法使用 verify/:id 之类的 URL 发出 GET http 请求 param(:id)我使用 @angular/router 中的 ActivatedRoute 获取它,以便我可以发出请求。
为了解决这个问题,建议我使用以下代码供我的 express 使用:
app.use(express.static(path.join(__dirname, 'client/dist')));
app.get('*', function(req, res) {
res.sendFile(__dirname + '/client/dist/index.html');
})
甚至尝试过:
app.all('*', function(req, res) {
res.sendFile(__dirname + '/client/dist/index.html');
})
此代码适用于直接导航(在搜索栏上粘贴 URL),并且仅针对 POST 和 PUT 请求刷新,但不适用于 GET requestS 期望来自服务器端的响应,当我直接访问 URL 或刷新页面时,DOM 是用服务器响应编写的,而不是 HTML,任何帮助将不胜感激。
最佳答案
定义完所有路由后,添加index.html文件的路由
// Set your routes here
app.use('/api', api);
// Catch all other routes and return the index file
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'path/to/index.html')); //path from the root dir
});
这对我来说是工作。 谢谢
关于node.js - 带参数的 Angular 和 NodeJS GET 请求 url 仅返回响应对象,无组件 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44905466/