emptygif
語言: 繁體中文

所有語言和框架

Angular SSR (Express server.ts) TypeScript

適用於 Angular SSR (Express server.ts) 的 TypeScript 程式碼片段,以空 GIF 回應對 /pixel.gif 的請求,GIF 在啟動時只解碼一次。

Angular SSR (Express server.ts) TypeScript

安裝
ng new my-app --ssr
檔案
server.ts
執行
ng build && node dist/my-app/server/server.mjs
// src/server.ts from `ng new --ssr`, with the pixel route ahead of Angular rendering.
import {
  AngularNodeAppEngine,
  createNodeRequestHandler,
  isMainModule,
  writeResponseToNodeResponse,
} from '@angular/ssr/node';
import express from 'express';
import { join } from 'node:path';

const GIF = Buffer.from('R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==', 'base64');

const browserDistFolder = join(import.meta.dirname, '../browser');

const app = express();
const angularApp = new AngularNodeAppEngine();

app.get('/pixel.gif', (req, res) => {
  res.type('gif').set('Cache-Control', 'no-store').send(GIF);
});

app.use(express.static(browserDistFolder, { maxAge: '1y', index: false, redirect: false }));

app.use((req, res, next) => {
  angularApp
    .handle(req)
    .then((response) => (response ? writeResponseToNodeResponse(response, res) : next()))
    .catch(next);
});

if (isMainModule(import.meta.url) || process.env['pm_id']) {
  const port = process.env['PORT'] || 4000;
  app.listen(port, (error) => {
    if (error) throw error;
    console.log(`Node Express server listening on http://localhost:${port}`);
  });
}

export const reqHandler = createNodeRequestHandler(app);

我們執行了這段程式碼,並比對了它回傳的位元組。

驗證

curl -sI http://localhost:8080/pixel.gif

官方網站: Angular SSR (Express server.ts)

更多 TypeScript 範例