5,337
edits
Line 81: | Line 81: | ||
RewriteRule ^ /index.html | RewriteRule ^ /index.html | ||
</pre> | </pre> | ||
}} | |||
===Express=== | |||
How to setup an Express server to host your Angular web application: | |||
{{ hidden | Route | | |||
First setup CSRF Protection: | |||
<syntaxhighlight lang="typescript"> | |||
this.csrfProtection = csurf({cookie: true}); | |||
this.app.use(this.csrfProtection); | |||
this.app.all( | |||
'*', | |||
(req: Request, res: Response, next: NextFunction): void => { | |||
res.cookie('XSRF-TOKEN', req.csrfToken()); | |||
next(); | |||
} | |||
); | |||
</syntaxhighlight> | |||
Then setup your routes to serve your frontend: | |||
<syntaxhighlight lang="typescript"> | |||
if (CONFIG.app.useProxy) { | |||
const myProxy = httpProxy.createProxyServer({ws: true}); | |||
console.log(`Proxying to ${CONFIG.app.appProxy}`); | |||
router.all('/*', (req: Request, res: Response, next: NextFunction) => { | |||
myProxy.web( | |||
req, | |||
res, | |||
{target: req.protocol + '://' + CONFIG.app.appProxy} | |||
); | |||
}); | |||
} else { | |||
router.all('/*', express.static(CONFIG.app.appFolder)); | |||
router.all('/*', (req: Request, res: Response, next: NextFunction) => { | |||
res.status(200).sendFile('index.html', {root: CONFIG.app.appFolder}); | |||
}); | |||
} | |||
</syntaxhighlight> | |||
If you are proxying for development, you will also need to proxy websockets: | |||
<syntaxhighlight lang="typescript> | |||
server.on( | |||
'upgrade', | |||
(request: http.IncomingMessage, socket: net.Socket, head: Buffer) => { | |||
const pathname = url.parse(request.url).pathname; | |||
if (pathname === '/backend') { | |||
this.wss.handleUpgrade(request, socket, head, ws => { | |||
this.wss.emit('connection', ws); | |||
}); | |||
} else if (CONFIG.app.useProxy) { | |||
console.log('proxying websocket'); | |||
myProxy.ws(request, socket, head, { | |||
target: 'ws://' + CONFIG.app.appProxy, | |||
}); | |||
} else { | |||
socket.destroy(); | |||
} | |||
} | |||
); | |||
</syntaxhighlight> | |||
}} | }} | ||