【问题标题】:Trouble passing Heroku config var through Node.js to Angular CLI app无法通过 Node.js 将 Heroku 配置变量传递给 Angular CLI 应用程序
【发布时间】:2017-09-22 22:24:14
【问题描述】:

我正在做一个项目,我需要在 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 结帐的代码

 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 应用程序?

谢谢!

附:这是我收到的错误..

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 ******* 我在 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:

现在查看文档。

**** 仍然在这里挣扎

****更新(这么多) 将 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 

【问题讨论】:

    标签: javascript angularjs node.js http heroku


    【解决方案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 请求,但您的客户端正在尝试获取每个路由器不存在的请求(this.http.get() 在您的 .ts 文件中)

    您的新路线将是:

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

    【讨论】:

    • 我将 res.send 更改为 res.json 但仍然出现错误。错误编辑见上文。
    • 抱歉,您没有注意到您正在尝试从客户端获取,但您的 Express 路由器正在定义一个 POST 请求。你能用 router.get() 代替 router.post() -- router.get('/stripetestkey', function(req, res) { res.json({ 'KeyCode': process.env.STRIPE_KEY }); });
    • 我按照你说的改了。我仍然遇到同样的错误。我尝试在开发环境中直接在对象中传递密钥,并得到上面 Stripe 给出的错误。我可能还缺少其他东西,我只是不确定那是什么。
    • 如果您要返回 JSON,然后解析 JSON,则需要获取该 JSON 的相应密钥。所以如果你的服务器返回的是 JSON 对象 {"KeyCode", "value"},下面需要从返回的对象中获取 KeyCode: 所以下面的this.keyService.getKey().subscribe(data =&gt; this.stripeTestKey = data); 变成了this.keyService.getKey().subscribe(data =&gt; this.stripeTestKey = data.KeyCode);
    • 另外,上面的错误 ({_body: "&lt;!DOCTYPE html&gt;↵&lt;html lang="en"&gt;↵&lt;head&gt;↵&lt;meta char…body&gt;↵&lt;pre&gt;Cannot GET /key&lt;/pre&gt;↵&lt;/body&gt;↵&lt;/html&gt;↵", status: 404...) 表明您正在尝试请求 /key 路由,这不是您发送 KeyCode 的路由。您的设置是 /stripetestkey在您的路由器中,因此客户端需要请求该路由。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    相关资源
    最近更新 更多