Angular Universal 构建一个 RESTful API

huangapple go评论51阅读模式
英文:

Angular Universal build a RESTful API

问题

创建新的Angular Universal应用程序时,会生成一个server.ts文件,用于处理服务器端渲染(SSR)过程。如果您需要发出服务器请求来执行后端功能,似乎必须使用采用的服务器框架Express.js构建一个RESTful API,正如这两个示例这里这里所描述的那样。但是,这两个示例都已经超过四年了。

要执行后端功能,我是否需要扩展生成的server.ts文件,如上述链接中所描述的?或者,Angular Universal是否提供了不同的方法或模式?与Angular组件或服务相比,我是否可以在此服务中运行后端功能?

我理解需要一个HTTP请求的实现,其中Express服务器会监听它。然而,我期望Angular Universal提供了一个额外的层次来简化这个过程。

由Angular Universal生成的server.ts文件:

import 'zone.js/node';

import { APP_BASE_HREF } from '@angular/common';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { AppServerModule } from './src/main.server';

// 导出Express应用程序,以便它可以被无服务器函数使用。
export function app(): express.Express {
  const server = express();
  const distFolder = join(process.cwd(), 'dist/antiquetrade-ssr/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';

  // 我们的Universal express-engine(在https://github.com/angular/universal/tree/main/modules/express-engine找到)
  server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule
  }));

  server.set('view engine', 'html');
  server.set('views', distFolder);

  // 示例Express Rest API端点
  // server.get('/api/**', (req, res) => { });
  // 从/browser目录下提供静态文件
  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));

  // 所有常规路由使用Universal引擎
  server.get('*', (req, res) => {
    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });

  return server;
}

function run(): void {
  const port = process.env['PORT'] || 4000;

  // 启动Node服务器
  const server = app();
  server.listen(port, () => {
    console.log(`Node Express服务器正在监听http://localhost:${port}`);
  });
}

// Webpack将使用'__webpack_require__'替换'require'
// '__non_webpack_require__'是Node 'require'的代理
// 以下代码是为了确保仅在不需要捆绑时运行服务器。
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  run();
}

export * from './src/main.server';

<details>
<summary>英文:</summary>
When creating a new Angular Universal app, a server.ts file is generated to handle the server-side rendering (SSR) process. If you need to make a server request to execute a backend function, it seems that you have to build a RESTful API using the adopted server framework Express.js as those two examples [here][1] and [here][2] describe. However, both examples are older than four years. 
To execute backend functions, do I need to extend the generated server.ts file as described in the aforementioned links? Alternatively, does Angular Universal offer a different approach or pattern? Something compare to angular component or service, where I can also run the backend function within this service.
I understand that there needs to be an implementation of an http request, where the Express server listens for it. However, I expected that Angular Universal provides an additional layer to simplify this process. 
server.ts file generated by angular universal:
import &#39;zone.js/node&#39;;
import { APP_BASE_HREF } from &#39;@angular/common&#39;;
import { ngExpressEngine } from &#39;@nguniversal/express-engine&#39;;
import * as express from &#39;express&#39;;
import { existsSync } from &#39;node:fs&#39;;
import { join } from &#39;node:path&#39;;
import { AppServerModule } from &#39;./src/main.server&#39;;
// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
const server = express();
const distFolder = join(process.cwd(), &#39;dist/antiquetrade-ssr/browser&#39;);
const indexHtml = existsSync(join(distFolder, &#39;index.original.html&#39;)) ? &#39;index.original.html&#39; : &#39;index&#39;;
// Our Universal express-engine (found @ https://github.com/angular/universal/tree/main/modules/express-engine)
server.engine(&#39;html&#39;, ngExpressEngine({
bootstrap: AppServerModule
}));
server.set(&#39;view engine&#39;, &#39;html&#39;);
server.set(&#39;views&#39;, distFolder);
// Example Express Rest API endpoints
// server.get(&#39;/api/**&#39;, (req, res) =&gt; { });
// Serve static files from /browser
server.get(&#39;*.*&#39;, express.static(distFolder, {
maxAge: &#39;1y&#39;
}));
// All regular routes use the Universal engine
server.get(&#39;*&#39;, (req, res) =&gt; {
res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
});
return server;
}
function run(): void {
const port = process.env[&#39;PORT&#39;] || 4000;
// Start up the Node server
const server = app();
server.listen(port, () =&gt; {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
// Webpack will replace &#39;require&#39; with &#39;__webpack_require__&#39;
// &#39;__non_webpack_require__&#39; is a proxy to Node &#39;require&#39;
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule &amp;&amp; mainModule.filename || &#39;&#39;;
if (moduleFilename === __filename || moduleFilename.includes(&#39;iisnode&#39;)) {
run();
}
export * from &#39;./src/main.server&#39;;
[1]: https://stackoverflow.com/questions/44734307/how-to-make-http-post-request-in-angular-4-universal
[2]: https://github.com/SinghDigamber/angular-universal-crud
</details>
# 答案1
**得分**: 2
Angular不是一个可以运行任何后台服务的框架。Angular Universal 主要负责在服务器上渲染应用程序。在你的 server.ts 文件中,你可以看到以下代码:
```typescript
// 示例 Express Rest API 端点
// server.get('/api/**', (req, res) => { });

在这里,你可以按照常规的 Express 框架模式来运行服务器上的任务(如果需要)。总体而言,Angular Universal 不像其他 SSR 框架,比如 Laravel。它只是将 Angular 绑定到 Express 服务器,以便在服务器上渲染 Angular 应用程序。

英文:

Angular is not such a frame work where you can run any back ground service. Angular universal is mainly responsible for rendering the app on the server.
In your server.ts file you can see this following lines

// Example Express Rest API endpoints
// server.get(&#39;/api/**&#39;, (req, res) =&gt; { });

Here, you can follow the regular express framework patterns in order to run tasks on server if needed. Overall, angular universal is not like other ssr frame works such as laravel. It's just binding angular to an express server in order to render the angular app on the server.

huangapple
  • 本文由 发表于 2023年5月29日 18:19:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76356481.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定