在Heroku上部署的Angular App上的代理路由

时间:2019-01-22 02:46:47

标签: node.js angular heroku

我有一个正在与REST服务通信的Angular应用。

当我使用CLI在本地运行Angular应用程序时,可以正确地将所有/api请求代理到REST服务。当我尝试构建应用并运行server.js(以便可以将应用部署到Heroku)时,我失去了代理路由。

REST服务已部署在Heroku上并且运行良好。

我使用以下命令运行Angular

ng serve

我的proxy.conf.json

{
  "/api": {
    "target": "https://my-app.herokuapp.com",
    "secure": true,
    "changeOrigin": true
  }
}

我按照this article中的描述创建了一个server.js,以便可以部署到Heroku上。

// server.js
const express = require('express');
const app = express();
const path = require('path');

// If an incoming request uses
// a protocol other than HTTPS,
// redirect that request to the
// same url but with HTTPS
const forceSSL = function () {
    return function (req, res, next) {
        if (req.headers['x-forwarded-proto'] !== 'https') {
            return res.redirect(
                ['https://', req.get('Host'), req.url].join('')
            );
        }
        next();
    }
}
// Instruct the app
// to use the forceSSL
// middleware
app.use(forceSSL());

// Run the app by serving the static files
// in the dist directory
app.use(express.static(__dirname + '/dist'));

// For all GET requests, send back index.html
// so that PathLocationStrategy can be used

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

// Start the app by listening on the default
// Heroku port
app.listen(process.env.PORT || 4200);

我还在package.json脚本中设置了安装后版本:

{
  "name": "catalog-manager-client",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "node server.js",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "postinstall": "ng build --aot"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.0.3",
    "@angular/cdk": "^6.2.1",
    "@angular/cli": "~6.0.8",
    "@angular/language-service": "^6.0.3",
    "@angular/common": "^6.0.3",
    "@angular/compiler": "^6.0.3",
    "@angular/compiler-cli": "^6.0.3",
    "@angular/core": "^6.0.3",
    "@angular/flex-layout": "^6.0.0-beta.16",
    "@angular/forms": "^6.0.5",
    "@angular/http": "^6.0.3",
    "@angular/material": "^6.2.1",
    "@angular/platform-browser": "^6.0.3",
    "@angular/platform-browser-dynamic": "^6.0.3",
    "@angular/router": "^6.0.3",
    "@swimlane/ngx-charts": "^8.0.2",
    "@swimlane/ngx-datatable": "^13.0.1",
    "core-js": "^2.5.4",
    "express": "^4.16.4",
    "hammerjs": "^2.0.8",
    "jquery": "^3.3.1",
    "moment": "^2.22.2",
    "ngx-perfect-scrollbar": "^6.2.0",
    "ngx-quill": "^3.2.0",
    "rxjs": "^6.0.0",
    "rxjs-compat": "^6.2.1",
    "rxjs-tslint": "^0.1.4",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.6.8",
    "typescript": "~2.7.2",
    "@types/jasmine": "~2.8.6",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.2.1",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~1.7.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.0",
    "karma-jasmine": "~1.1.1",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.3.0",
    "ts-node": "~5.0.1",
    "tslint": "~5.9.1"
  },
  "engines": {
    "node": "9.11.2",
    "npm": "6.5.0"
  }
}

我是Angular的新手,所以我可能犯了一个根本性的错误,但是如何修改server.js以使用proxy.conf.json设置?

1 个答案:

答案 0 :(得分:0)

解释属于是,您犯了一个基本错误类别,但是我已经看到了足够多的类似问题,我认为解释可能会对下一个开发人员有所帮助。

Angular CLI正在运行完整的http服务器。 Angular UI已完全编译,并且CLI从/dist目录将其作为静态内容提供。

proxy.conf.json设置用于由Angular CLI运行的服务器,它与您的编译代码无关。

当您从本地环境移至Heroku之类时,您需要一台服务器来代替Angular CLI。这是node.jsexpress的所有示例的加入之处。它们向您介绍的简单server.js文件足以设置基本的静态内容服务器。很好,因为您的Angular代码是静态内容!

但是,如果您需要通过proxy.conf.json路由到动态后端服务器,那么简单的静态服务器对此一无所知。

在我的情况下,我的后端服务器在Koa上运行,因此我在Angular代码中添加了静态路由。

const router = require('koa-router')();
const body = require('koa-body')({ text: false });
const send = require('koa-send');
const fs = require('fs');

/**
 * Code about server routes ommited
 */

async function main(ctx, next) {
    //All dynamic routes start with "/api"
    if (/\/api\//.test(ctx.path)) {
        try {
            await next();
        }
        catch (error) {
            if (error instanceof ApplicationError) {
                logger.error(error, { data: error.data, stack: error.stack });
                ctx.status = error.code;
            } else {
                ctx.status = 500;
                logger.error(error.message, { stack: error.stack });
            }
        }
        return;
    } else {
        //Not a dynamic route, serve static content
        if ((ctx.path != "/") && (fs.existsSync('dist' + ctx.path))) {
            await send(ctx, 'dist' + ctx.path);
        } else {
            await send(ctx, 'dist/index.html');
        }
    }
}

module.exports = app => {
    app.use(main);
    app.use(router.routes());
};

注意-对于任何类型的高工作负载,这都不是一种高性能的解决方案,但是如果您有一个很小的项目,并不能证明花费资源来设置可扩展性更高的产品,直到变大为止都可以使用。