angular/integration/platform-server/projects/ngmodule/server.ts
Alan Agius 405ec8c796 fix(platform-server): resolve relative requests URL (#52326)
Prior to this commit relative HTTP requests were not being resolved to absolute even thought the behaviour is documented in https://angular.io/guide/universal#using-absolute-urls-for-http-data-requests-on-the-server.

This caused relative HTTP requests to fail when done on the server because of missing request context. This change is also required to eventually support HTTP requests handled during prerendering (SSG).

Closes #51626

PR Close #52326
2023-10-23 12:02:21 -07:00

55 lines
1.4 KiB
TypeScript

/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/* tslint:disable:no-console */
import 'zone.js/node';
import {APP_BASE_HREF} from '@angular/common';
import {renderModule} from '@angular/platform-server';
import * as express from 'express';
import {AppServerModule} from './src/main.server';
import {join} from 'path';
import {readFileSync} from 'fs';
import './prerender';
const app = express();
const distFolder = join(process.cwd(), 'dist/ngmodule/browser');
const indexHtml = readFileSync(join(distFolder, 'index.html'), 'utf-8');
// Serve static files from /browser
app.get(
'*.*',
express.static(distFolder, {
maxAge: '1y',
})
);
// Mock API
app.get('/api', (req, res) => {
res.json({data: 'API 1 response'});
});
app.get('/api-2', (req, res) => {
res.json({data: 'API 2 response'});
});
// All regular routes use the Universal engine
app.get('*', (req, res) => {
const { protocol, originalUrl, baseUrl, headers } = req;
renderModule(AppServerModule, {
document: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
extraProviders: [{provide: APP_BASE_HREF, useValue: baseUrl}],
}).then((response: string) => {
res.send(response);
});
});
app.listen(4206, () => {
console.log('Server listening on port 4206!');
});