-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
66 lines (58 loc) · 1.69 KB
/
server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { APP_BASE_HREF } from "@angular/common"
import { CommonEngine, isMainModule } from "@angular/ssr/node"
import express from "express"
import { dirname, join, resolve } from "node:path"
import { fileURLToPath } from "node:url"
import AppServerModule from "./main.server"
const serverDistFolder = dirname(fileURLToPath(import.meta.url))
const browserDistFolder = resolve(serverDistFolder, "../browser")
const indexHtml = join(serverDistFolder, "index.server.html")
const app = express()
const commonEngine = new CommonEngine()
/**
* Example Express Rest API endpoints can be defined here.
* Uncomment and define endpoints as necessary.
*
* Example:
* ```ts
* app.get('/api/**', (req, res) => {
* // Handle API request
* });
* ```
*/
/**
* Serve static files from /browser
*/
app.get(
"**",
express.static(browserDistFolder, {
maxAge: "1y",
index: "index.html"
})
)
/**
* Handle all other requests by rendering the Angular application.
*/
app.get("**", (req, res, next) => {
const { protocol, originalUrl, baseUrl, headers } = req
commonEngine
.render({
bootstrap: AppServerModule,
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: browserDistFolder,
providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }]
})
.then(html => res.send(html))
.catch(err => next(err))
})
/**
* Start the server if this module is the main entry point.
* The server listens on the port defined by the `PORT` environment variable, or defaults to 4000.
*/
if (isMainModule(import.meta.url)) {
const port = process.env["PORT"] || 3001
app.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`)
})
}