简体   繁体   中英

Running an angular project with node.js

I've an angular project that I can run without issues with ng serve . But I have to use node.js to have access to a DB.

I've created a file 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:

<!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. 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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