首页 > 解决方案 > 如何在同一个文件夹中安装 Angular 和 Nodejs

问题描述

我是新手,NodeJs并且Angular我使用此链接创建了简单的 Nodejs 应用程序,但没有关于如何在 Nodejs 旁边安装 Angular 的示例。我尝试ng new angular-crud在根文件夹中运行,它在angular-crud文件夹中创建了文件root夹。现在我有 2 个 node_modules 文件夹,第一个在root文件夹中,第二个在angular-crud文件夹中。

a) INSTALL ::如何安装 Angular 以便始终只有一个 node_modules 文件夹。

b) RUN ::Nodejs 应用程序使用命令node app.jswhere app.jsis theentry point但另一方面 Angular 应用程序使用ng serve. 如果我同时安装了 Nodejs 和 Angular,那么如何运行该应用程序。

c)结构:: 当同时使用 Node 和 Angular 时,理想的文件夹结构应该是什么。

我的 package.json 文件:

{
  "name": "test-na",
  "version": "0.0.1",
  "dependencies": {
    "body-parser": "^1.18.3",
    "cors": "^2.8.4",
    "express": "^4.16.3"
  },
  "description": "test",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

我的 app.js 文件:

const bodyParser = require('body-parser');
const express = require('express');
const cors = require('cors');
const app = express();

var corsOptions = {
    origin: 'http://example.com',
    optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};

app.use(bodyParser.json());
app.use(cors(corsOptions));


app.route('/api/cats').get((req, res) => {
    res.send({
        cats: [{ name: 'lilly' }, { name: 'lucy' }]
    });
});

app.route('/api/cats').post((req, res) => {
    res.send(201, req.body);
});

app.route('/api/cats/:name').get((req, res) => {
    const requestedCatName = req.params['name'];
    res.send({ name: requestedCatName });
});

app.route('/api/cats/:name').put((req, res) => {
    res.send(200, req.body);
});

app.route('/api/cats/:name').delete((req, res) => {
    res.sendStatus(204);
});

app.listen(8000, () => {
    console.log('Server started');
});

标签: javascriptnode.jsangularexpress

解决方案


Angular 旨在创建单页应用程序:如果您不执行服务器端渲染,您可能不应该在 nodeJs 应用程序中嵌入 Angular 应用程序。

相反,Angular 应用程序应该存在于它自己的文件夹中(通常在它自己的服务器中),并通过触发 API 调用与 nodeJs 应用程序连接。

例如,您可以使用域https://acme.com为 Angular 应用程序提供静态服务,并且您的 Angular 应用程序将针对https://acme.com/api/v1/执行 api 请求。

除非您需要服务器端渲染(我对 Angular SSR 几乎一无所知),否则在 nodeJs 应用程序中嵌入 Angular 可能不会获得任何好处。如果您遵循 Angular 部署指南,您将看到服务和部署 Angular 应用程序的预期形式是从 Apache 或 Ngnx 静态地服务 Angular 应用程序。


推荐阅读