javascript - 如何在同一个文件夹中安装 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.js
where app.js
is 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');
});
解决方案
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 应用程序。
推荐阅读
- javascript - 如何在对象中分配对象
- ruby - 默认使用空数组初始化 Ruby 哈希
- javascript - 如何获得纯色背景色和半透明叠加色的有效结果(6位十六进制值)?
- javascript - 一个函数在它应该执行之前执行
- javascript - 在 hooks.js 文件中添加 BeforeScenario 时,Selenium-cucumber.js 测试无法运行
- python - Python:使用熊猫匹配替换部分文件路径
- android - imageView 导致父布局在约束布局中收缩
- javascript - 您可以在引导模式上使用“x”(关闭)按钮来调用 javascript 函数而不是关闭模式吗?
- r - R Shiny - 我真的需要所有这些 REACTIVE 功能吗?
- django - 尽管将 required attr 设置为 false,但仍需要表单字段