簡體   English   中英

無法通過Node.js將Heroku配置變量傳遞給Angular CLI應用程序

[英]Trouble passing Heroku config var through Node.js to Angular CLI app

我正在一個項目中,我需要在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;

這是服務提供者(在應用程序模塊中並正確注入),從服務器獲取密鑰

//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 checkout的代碼

 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 config var傳遞給我的angular應用程序該怎么做嗎?

謝謝!

PS這里是我收到的錯誤..

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 

更新**我將res.send更改為server.js中的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 *******我已將server.js中的router.post更改為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:

現在簽出文檔。

****還在這里掙扎

在此處輸入圖片說明

**** UPDATE(太多)將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 

使用res.json()而不是res.send()

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

鏈接以在res.json()上表達文檔: https : res.json()

根據您收到的404錯誤進行編輯:

確保使用路由器定義的動詞(GET,POST等)請求相同的資源。 在您的情況下,您正在ExpressJS中定義POST請求,但是您的客戶this.http.get()在嘗試獲取每個路由器都不存在的請求this.http.get() .ts文件中的this.http.get()

您的新路線將是:

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

更新以幫助說明如何確保在this.stripeTestKey handler.open()之前設置this.stripeTestKey

由於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)
    });
  });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM