简体   繁体   中英

How to setup express and node into an existing front-end only Angular 2 project?

I have a current front-end only Angular 2 application using the Angular-CLI and NPM. I want visitors to be able to send me emails through the contact form.

For this I obviously need a back-end, express and node, in which I have no experience in using.

I need to intergrate express and node into my app but I dont know how to do this correctly.

I have found THIS similar question on SO but its not relevant to my situation.

Other tutorials only show how to scaffold a MEAN stack app not intergrate the backend after the front end has been built.

What I would like to know :

  • How do I set up my Angular 2 App to use express and node for the back end?
  • What are the relevant files I need?
  • Can I do this by using the Angular-CLI?

The best way to setup a project that is built using angular-cli to use a nodejs/express backend is to simple create an express project that serves up a directory. In your client project, if it has been created using the angular-cli, you should be able to just type in ng build and it will compile everything into a dist directory.

From there, you can create an express server that serves up that dist directory like so:

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

The most simple server you could build would probably something like

var express = require('express')
var path = require('path');

var app = express()

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
});

This will intercept all routes and redirect them to the index.html file in the dist/ folder that was created.

For more information on how to set this up and some more advanced settings, check out these links:

Just think about the dist/ folder as static files that will be served over an express server, and because routing and everything is handled through angular, you'll be set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM