麻烦将Heroku config var通过Node.js传递给Angular CLI app

时间:2017-04-25 18:40:25

标签: javascript angularjs node.js http heroku

我正在开发一个项目,我需要在Angular中将条带键作为JSON传递。

我在Config vars中添加了Heroku的密钥,并尝试通过Heroku教程中声明的process.env.STRIPE_KEY方法将该值通过Node.js后端传递给Angular。我完全迷失了,不确定我是否正确地走这条路。

这是我的节点服务器文件。

//server.js
const express = require('express');
const app = express();
const bodyParser = require("body-parser");
const router = express.Router();


app.use(express.static(__dirname + '/dist'));
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({extended: true}));

app.listen(3000, function(){});

router.all('*',function(req,res,next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
  res.header("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS");
  next();

});



router.post('/stripetestkey', function(req, res) {
  res.json({
    'STRIPE_TEST_API_KEY': process.env.STRIPE_KEY
  });
});


module.exports = router;

以下是从服务器获取密钥的服务提供商(在app模块中并正确注入)

//service.ts

import {Injectable} from "@angular/core";
import {Http, Headers} from "@angular/http";
import 'rxjs/add/operator/map';
import {Observable} from "rxjs";

@Injectable()
export class KeyService {
  constructor(private http: Http) {}

  private getError(error: Response): Observable<any>{
    console.log(error);
    return Observable.throw(error.json() || 'Server Issue');
  }

  getKey(): Observable<any> {
    let headers = new Headers();
    headers.append('Content-type', 'application/json');
    return this.http.get('http://localhost:3000/stripetestkey',{ headers: headers })
      .map(res => res.json())
      .catch(this.getError);
  }


}

这是我用正确的密钥

打开Stripe结帐的代码
 openCheckout() {
    this.keyService.getKey().subscribe(data => this.stripeTestKey = data.STRIPE_TEST_API_KEY);
    let handler = (<any>window).StripeCheckout.configure({
      key: this.stripeTestKey,
      locale: 'auto',
      token: function (token: any) {

      }
    });
    handler.open({
      name: 'XXXXXX',
      description: 'Donation',
      amount: (this.donation * 100)
    });
  }

我一直在使用HTML而不是JSON,我只是不确定我是否正确地使用了这个。我还试过传递JSON而不是process.env.STRIPE_KEY。任何人都可以让我知道我需要做什么来通过node.js将heroku配置var传递给我的角度应用程序?

谢谢!

P.S。这是我收到的错误..

Failed to load resource: the server responded with a status of 404 (Not Found)
main.bundle.js:32 Response
vendor.bundle.js:1443 ERROR SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at Response.Body.json 

更新** 我在server.js中将res.send更改为res.json,这是我得到的更新错误。

keys.service.ts:11 Response {_body: "<!DOCTYPE html>↵<html lang="en">↵<head>↵<meta char…body>↵<pre>Cannot GET /stripetestkey</pre>↵</body>↵</html>↵", status: 404, ok: false, statusText: "Not Found", headers: Headers…}


core.es5.js:1084 ERROR SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at Response.Body.json (http.es5.js:796)

更新#2 ******* 我已将router.post更改为server.js中的router.get。我仍然得到上述相同的错误。我尝试直接将密钥作为对象传递

router.get('/stripetestkey', function(req, res) {
  res.json({
    'STRIPE_TEST_API_KEY': 'pk_test_XXXXXXXXXXXXXXXXXX'
  });
});

并且Stripe为我返回了此错误。

StripeCheckout.configure: Type mismatch for option 'key':
Looking for type 'string', but instead we found 'object'.
You can learn about the available configuration options in the Checkout docs:

立即查看文档。

****仍然在这里苦苦挣扎

enter image description here

****更新(这么多) 将http://localhost:3000/stripetestkey更改为https://localhost:3000/keys(还将服务器端更改为/ keys以便正确路由(更容易理解)。

OPTIONS https://localhost:3000/keys net::ERR_CONNECTION_CLOSED
scheduleTask @ zone.js:1990
webpackJsonp.585.ZoneDelegate.scheduleTask @ zone.js:384
onScheduleTask @ zone.js:274
webpackJsonp.585.ZoneDelegate.scheduleTask @ zone.js:378
webpackJsonp.585.Zone.scheduleTask @ zone.js:209
webpackJsonp.585.Zone.scheduleMacroTask @ zone.js:232
(anonymous) @ zone.js:2014
send @ VM1198:3
(anonymous) @ http.es5.js:1254
Observable._trySubscribe @ Observable.js:57
Observable.subscribe @ Observable.js:45
MapOperator.call @ map.js:54
Observable.subscribe @ Observable.js:42
CatchOperator.call @ catch.js:79
Observable.subscribe @ Observable.js:42
webpackJsonp.237.NavbarComponent.openCheckout @ navbar.component.ts:74
(anonymous) @ NavbarComponent.html:40
handleEvent @ core.es5.js:11798
callWithDebugContext @ core.es5.js:13006
debugHandleEvent @ core.es5.js:12594
dispatchEvent @ core.es5.js:8773
(anonymous) @ core.es5.js:9363
(anonymous) @ platform-browser.es5.js:2683
webpackJsonp.585.ZoneDelegate.invokeTask @ zone.js:398
onInvokeTask @ core.es5.js:4116
webpackJsonp.585.ZoneDelegate.invokeTask @ zone.js:397
webpackJsonp.585.Zone.runTask @ zone.js:165
ZoneTask.invoke @ zone.js:460
keys.service.ts:11 

1 个答案:

答案 0 :(得分:1)

使用res.json()代替res.send()

router.post('/stripetestkey', function(req, res) {
  res.json({
    'KeyCode': process.env.STRIPE_KEY
  });
});

链接到res.json()上的快速文档:https://expressjs.com/en/api.html#res.json

根据您获得的404错误进行编辑:

确保您使用与路由器定义的相同的动词(GET,POST等)请求相同的资源。在您的情况下,您在ExpressJS中定义POST请求,但您的客户端正在尝试获取您的路由器(.ts文件中的this.http.get())不存在的请求。

您的新路线将是:

router.get('/stripetestkey', function(req, res) {
  res.json({
    'KeyCode': process.env.STRIPE_KEY
  });
});

更新以帮助说明如何确保在this.stripeTestKey

之前设置handler.open()

因为this.keyService.getKey().subscribe()是异步的,所以在设置this.stripTestKey之前会调用handler.open()。你可以做类似以下的事情来修复你的.subscribe()回调:

openCheckout() {
  this.keyService.getKey().subscribe(data => {
    this.stripeTestKey = data.STRIPE_TEST_API_KEY

    let handler = (<any>window).StripeCheckout.configure({
      key: this.stripeTestKey,
      locale: 'auto',
      token: function (token: any) {

      }
    });
    handler.open({
      name: 'XXXXXX',
      description: 'Donation',
      amount: (this.donation * 100)
    });
  });
}