How to setup express and node into an existing fro

2020-06-06 20:17发布

问题:

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?

回答1:

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:

  • http://expressjs.com/en/starter/installing.html
  • https://scotch.io/tutorials/mean-app-with-angular-2-and-the-angular-cli

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.