简体   繁体   English

Angular 2'app-root'未在ExpressJS路由上加载

[英]Angular 2 'app-root' not loading on ExpressJS route

Im new to NodeJS and Express but i want a simple '/' route to Angular's default index.html (client/src/index.html) which contains the app-root tag. 我是NodeJS和Express的新手,但我想要一个简单的'/'路由到Angular的默认index.html(client / src / index.html),它包含app-root标签。

The '/' route successfully serves the index.html file but it doesn't expand/load the 'app-root' tag into the component's html so i just get blank page. '/'路由成功地为index.html文件提供服务,但它不会将'app-root'标记扩展/加载到组件的html中,所以我只得到空白页面。

Im not sure why it cant resolve the app-root tag when routed from Express. 我不确定为什么它从Express路由时无法解析app-root标签。 Only if i run Angular by 'ng serve' does the index.html successfully load the contents of the app-root tag. 只有当我通过'ng serve'运行Angular时,index.html才能成功加载app-root标记的内容。

My structure is as follows: 我的结构如下:

/client
    /e2e
    /node_modules
    /app
        app.component.css/html/ts
        app.module.ts
    /src
        index.html
        main.ts
package.json
server.js

server.js server.js

var express = require('express');
var path = require('path');

var port = 80;

var app = express();

// set static folder
app.use(express.static(path.join(__dirname, '/client')));

app.get('/', function(req, res, next){
    res.sendFile(__dirname + '/client/src/index.html');
});

app.listen(port, function(){
    console.log("Server started on port " + port);
});

It look like you didn't do 'ng build' your angular app because main.ts is still there. 看起来你没有“建立”你的角度应用程序,因为main.ts仍在那里。

When you do the 'ng serve', angular compiles and serve it using webpack-dev-server. 当您执行'ng serve'时,angular编译并使用webpack-dev-server提供服务。

If you want to serve your app from the your node as static, you need a compiled angular app. 如果您希望从您的节点以静态方式提供应用程序,则需要一个已编译的角度应用程序。

You can do the following 您可以执行以下操作

$ cd client && ng build

There will be client/dist directory created where your compiled angular app is located and you can serve that on your express 将在您编译的角度应用程序所在的位置创建client / dist目录,您可以在快递上提供该目录

You can change the directory in you server.js like below 您可以更改server.js中的目录,如下所示

app.use(express.static(path.join(__dirname, '/client/dist')));
res.sendFile(__dirname + '/client/dist/index.html');

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM