emptygif
ภาษา: ไทย

ภาษาและเฟรมเวิร์กทั้งหมด

Angular SSR (Express server.ts) TypeScript

ตัวอย่างโค้ด TypeScript สำหรับ Angular SSR (Express server.ts) ที่ตอบคำขอไปยัง /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