emptygif
Ngôn ngữ: Tiếng Việt

Tất cả ngôn ngữ và framework

Angular SSR (Express server.ts) TypeScript

Đoạn mã TypeScript cho Angular SSR (Express server.ts), trả lời các yêu cầu tới /pixel.gif bằng GIF rỗng, được giải mã một lần khi khởi động.

Angular SSR (Express server.ts) TypeScript

Cài đặt
ng new my-app --ssr
Tệp
server.ts
Chạy
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);

Chúng tôi đã chạy đoạn mã này và so sánh các byte nó trả về.

Kiểm tra

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

Trang chính thức: Angular SSR (Express server.ts)

Thêm với TypeScript