简体   繁体   English

使用node.js运行角度项目

[英]Running an angular project with node.js

I've an angular project that I can run without issues with ng serve . 我一直认为我可以毫不问题进行运行的角度项目ng serve But I have to use node.js to have access to a DB. 但是我必须使用node.js才能访问数据库。

I've created a file server.js: 我创建了一个文件server.js:

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

app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, './','index.html'));
});

var port = process.env.PORT || 4800;

app.listen(port, (req,res) => {
    console.log(`RUNNING on port ${port}`);
});

And this index.html file: 而这个index.html文件:

<!doctype html>
<html lang="en">
<head>
      <meta charset="utf-8">
      <title>AngNode</title>
      <base href="/">

      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
      <app-root></app-root>

      <script type="text/javascript" src="runtime.js"></script><script type="text/javascript" src="polyfills.js"></script>
    <script type="text/javascript" src="styles.js"></script><script type="text/javascript" src="vendor.js"></script><script type="text/javascript" src="main.js"></script>
</body>
</html>

When I run the server.js file I got the RUNNING on port 4800 but when I open the browser I got nothing but a blank page and no error. 当我运行server.js文件时,我RUNNING on port 4800RUNNING on port 4800但是当我打开浏览器时,除了空白页面外,我什么也没有看到。 I tried to add a Hello World before the <app-root></app-root> and it's been displayed on the window but that's all. 我试图在<app-root></app-root>之前添加一个Hello World ,它已经显示在窗口中,仅此而已。

I don't have any error on my console or on the browser so I don't know how to correct it. 我的控制台或浏览器上没有任何错误,所以我不知道如何解决。

Thank you 谢谢

The problem is that your angular application is not running under 4800 but under 4200 (by default) so although you are not getting js errors you are probably getting 404 in the request tab. 问题是您的angular应用程序不是在4800下运行,而是在4200下运行(默认情况下),因此,尽管您没有遇到js错误,但在请求标签中却可能得到404错误。

You need to setup a proxy in your angular application (for development see https://juristr.com/blog/2016/11/configure-proxy-api-angular-cli/ ) or, in case you want to deliver the files from the express server, you need to compile the app, deploy the bundled version and configure your express to correctly deliver the files you need depending on the path. 您需要在angular应用程序中设置代理(有关开发,请参见https://juristr.com/blog/2016/11/configure-proxy-api-angular-cli/ ),或者,如果要从Express服务器,您需要编译应用程序,部署捆绑的版本并配置Express,以根据路径正确交付所需的文件。

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

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