96 lines
2.4 KiB
TypeScript
96 lines
2.4 KiB
TypeScript
import {
|
|
AngularNodeAppEngine,
|
|
createNodeRequestHandler,
|
|
isMainModule,
|
|
writeResponseToNodeResponse,
|
|
} from '@angular/ssr/node';
|
|
import express from 'express';
|
|
import { join } from 'node:path';
|
|
|
|
const browserDistFolder = join(import.meta.dirname, '../browser');
|
|
|
|
const app = express();
|
|
const angularApp = new AngularNodeAppEngine();
|
|
|
|
app.use(express.json());
|
|
|
|
/**
|
|
* Proxy /api requests to backend API server on port 7020
|
|
*/
|
|
app.use('/api', async (req, res) => {
|
|
try {
|
|
const backendUrl = `http://127.0.0.1:7020${req.originalUrl}`;
|
|
const headers = new Headers();
|
|
|
|
for (const [key, value] of Object.entries(req.headers)) {
|
|
if (value && key !== 'host' && key !== 'connection') {
|
|
headers.set(key, Array.isArray(value) ? value.join(', ') : value);
|
|
}
|
|
}
|
|
|
|
const fetchOptions: RequestInit = {
|
|
method: req.method,
|
|
headers,
|
|
};
|
|
|
|
if (!['GET', 'HEAD'].includes(req.method)) {
|
|
fetchOptions.body = JSON.stringify(req.body);
|
|
}
|
|
|
|
const apiRes = await fetch(backendUrl, fetchOptions);
|
|
res.status(apiRes.status);
|
|
|
|
apiRes.headers.forEach((val, key) => {
|
|
res.setHeader(key, val);
|
|
});
|
|
|
|
const buffer = await apiRes.arrayBuffer();
|
|
res.send(Buffer.from(buffer));
|
|
} catch (err) {
|
|
res.status(500).json({ error: 'SSR API Proxy failed', details: String(err) });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* Serve static files from /browser
|
|
*/
|
|
app.use(
|
|
express.static(browserDistFolder, {
|
|
maxAge: '1y',
|
|
index: false,
|
|
redirect: false,
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* Handle all other requests by rendering the Angular application.
|
|
*/
|
|
app.use((req, res, next) => {
|
|
angularApp
|
|
.handle(req)
|
|
.then((response) =>
|
|
response ? writeResponseToNodeResponse(response, res) : next(),
|
|
)
|
|
.catch(next);
|
|
});
|
|
|
|
/**
|
|
* Start the server if this module is the main entry point, or it is ran via PM2.
|
|
* The server listens on the port defined by the `PORT` environment variable, or defaults to 4000.
|
|
*/
|
|
if (isMainModule(import.meta.url) || process.env['pm_id'] || process.env['NODE_ENV'] === 'production') {
|
|
const port = process.env['PORT'] || 4000;
|
|
app.listen(port, (error) => {
|
|
if (error) {
|
|
throw error;
|
|
}
|
|
|
|
console.log(`Node Express server listening on http://localhost:${port}`);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Request handler used by the Angular CLI (for dev-server and during build) or Firebase Cloud Functions.
|
|
*/
|
|
export const reqHandler = createNodeRequestHandler(app);
|