Cloud Foundry 中的绑定服务不起作用

bind services in cloud foundry not working

我已经从市场创建了 postgress 服务(通过 cf create-service),我想在我的 node.js 应用程序中使用它。(我能够在本地测试它是否有效) 我有两个问题

1.i've tried the following and the application doesnt able to start and in the log I got this as my value for the env varible what am I missing here?

这是代码:

OK i've tried the following and the application doesnt able to start and in the log I got 

这是我的环境变量值,我在这里缺少什么?

     OUT env variable host: 10.0.97.139
     OUT port: 34807
     OUT user: qmxgvfybloierztm
     OUT password: mlofvwfsxmf7bqjr
     OUT database: r8n13yjyql7hwrgc
     OUT url: postgres://qmxgvfybloierztm:mlofvwfsxmf7bqjr@10.0.97.135:34607/r8n13yjyql7hwrgc
     OUT start create table
     OUT ERROR: connect: Error: connect ECONNREFUSED 10.0.97.135:5432




(function(){

    if (null == process.env.VCAP_SERVICES) {
        var url = 'postgress://localhost:27017/local';
    }
    else {
        var vcap_services = JSON.parse(process.env.VCAP_SERVICES);

        console.log("postgress URL: ", url);
    };

    var DBWrapper = require('node-dbi').DBWrapper;

    var dbConnectionConfig = {
        uri: vcap_services['postgresql'][0].credentials.uri,
        host: vcap_services['postgresql'][0].credentials.hostname,
        port: vcap_services['postgresql'][0].credentials.port,
        database: vcap_services['postgresql'][0].credentials.dbname,
        user: vcap_services['postgresql'][0].credentials.username,
        password: vcap_services['postgresql'][0].credentials.password
    };

    var dbWrapper = new DBWrapper('pg', dbConnectionConfig);

    dbWrapper.connect();

    console.log("start create table");
    dbWrapper.query("CREATE TABLE IF NOT EXISTS TAB1 ( firstname  TEXT primary key, lastname varchar(20) )", function (err, results) {
        if (err) {
            console.log("error while inserting data " + err);
        } else {
            console.log("success to insert data: ");
        }
    });

    })();

更新(在 Jerome 回答之后...)这就是我的所有代码!!!

"use strict";

var express = require("express");
var path = require("path");


var app = express();


var port = process.env.PORT || 3000;

app.listen(port, function () {


    (function () {


        var DBWrapper = require('node-dbi').DBWrapper;
        var vcap_services = JSON.loparse(process.env.VCAP_SERVICES);
        var pgconf = vcap_services['postgresql'][0].credentials;
        var dbConnectionConfig = {
            dsn: pgconf.uri
        };
        var dbWrapper = new DBWrapper('pg', dbConnectionConfig);
        dbWrapper.connect();


        console.log("env variable host: " + pgconf.hostname)
        console.log("port: " + pgconf.port);
        console.log("user: " + pgconf.user);
        console.log("password: " + pgconf.password);
        console.log("database: " + pgconf.database);
        console.log("url: " + pgconf.uri);


        console.log("start create table");
        dbWrapper.query("CREATE TABLE IF NOT EXISTS USER ( firstname  TEXT primary key, lastname varchar(20) )", function (err, results) {
            if (err) {

                console.log("error while inserting data " + err);
            } else {
                console.log("success to insert data: ");
            }
        });


        var data =
        {
            firstname: 'John5',
            lastname: 'Foo4444'
        };

        //insert data
        dbWrapper.insert('USER', data, function (err, data) {
            if (err) {
                console.log("error to insert data: " + err);
                // John has been inserted in our table, with its properties safely escaped
            } else {
                console.log("test" + data);
            }

        });

        //read data
        dbWrapper.fetchAll("SELECT * FROM USER", null, function (err, result) {
            if (!err) {
                console.log("Data came back from the DB.", result);
            } else {
                console.log("DB returned an error: %s", err);
            }

            dbWrapper.close(function (close_err) {
                if (close_err) {
                    console.log("Error while disconnecting: %s", close_err);
                }
            });
        });

    })();


});

现在我得到了这个错误

2016-07-26T11:55:49.69+0300 [App/0]      OUT env variable host: undefined
2016-07-26T11:55:49.69+0300 [App/0]      OUT port: 35058
2016-07-26T11:55:49.69+0300 [App/0]      OUT user: undefined
2016-07-26T11:55:49.69+0300 [App/0]      OUT password: hvevfgpjjtyqpr1d
2016-07-26T11:55:49.69+0300 [App/0]      OUT database: undefined
2016-07-26T11:55:49.69+0300 [App/0]      OUT url: postgres://fakttklwkxtfprgv:hvevfgpjjtyqpr1d@10.0.97.140:35058/ispkmc5psgdrwj4e
2016-07-26T11:55:49.69+0300 [App/0]      OUT start create table
2016-07-26T11:55:49.69+0300 [App/0]      OUT ERROR: connect: Error: getaddrinfo ENOTFOUND undefined undefined:5432

根据code of node-dbi,pg适配器建立连接url为

var cfg = this._connectionParams;
if (connectionParams["dsn"]) {
  this._pgUrl = connectionParams["dsn"];
} else {
  this._pgUrl = 'pg://'+cfg.user+':'+cfg.password+'@'+cfg.host+'/'+cfg.database;
}
this._dbClient = new pg.Client(this._pgUrl);

看到你的错误信息,

ERROR: connect: Error: connect ECONNREFUSED 10.0.97.135:5432

您的代码正在尝试连接到默认的 postgres 端口 5432,这暗示该端口未正确转发到 pg。 node-dbi 源代码不使用 cfg.port 变量,因此这可以解释您的错误,因为如果我们相信 postgres 实例应该正在侦听 pg 库,则永远不会为 pg 库提供 34607 端口 'url' post.

中显示的 ENV 变量

另请注意,node-dbi 更喜欢存在的 dsn :

this._pgUrl = connectionParams["dsn"];

您似乎在 ENV 中有 dsn,名称为 'url'。

很难从外部给你确切的修复,但我相信它应该适用于

var DBWrapper = require('node-dbi').DBWrapper;
var pgconf = vcap_services['postgresql'][0].credentials;
var dbConnectionConfig = {
    dsn: pgconf.url
};
var dbWrapper = new DBWrapper('pg', dbConnectionConfig);
dbWrapper.connect();

更新

给定的解决方案导致错误

OUT ERROR: connect: Error: getaddrinfo ENOTFOUND undefined undefined:5432

这往往表明 dsn 没有给出或没有被 pg 正确分析。这让我看到 node-dbi 使用了非常旧的 pg 版本。所以我们不应该尝试将连接参数用作字符串。

您确认您使用的 node-dbi 版本是 0.7.1 吗?

我刚刚安装了 node-dbi。它给了我 0.7.1,我可以在那里阅读

 var cfg = this._connectionParams;
 this._pgUrl = 'pg://' + cfg.user + ':' + cfg.password + '@' + cfg.host + '/' + cfg.database;
 this._dbClient = new pg.Client(this._pgUrl);

因此此代码与我们在 github 上看到的不匹配。此版本未处理 dsn。

这可以通过 https://github.com/DrBenton/Node-DBI/commits/master 确认。 0.7.1 版本日期为 2014 年 1 月,postgres dsn 处理日期为 2015 年 1 月,因此尚未发布...

你的日志中有一个差异,我不明白为什么它说主机未定义所以我将直接使用 uri 绕过它,因为 uri 似乎是正确的。

看到node-dbi如何构建pg连接串,可以试试

var url = require('url');
var DBWrapper = require('node-dbi').DBWrapper;
var pgconf = vcap_services['postgresql'][0].credentials;
console.log(pgconf.uri);
var parts = url.parse(pgconf.uri);
var dbConnectionConfig = {
    user: parts.auth.split(':')[0],
    password: parts.auth.split(':')[1],
    host: parts.host,
    database: parts.pathname.substr(1)
};
var dbWrapper = new DBWrapper('pg', dbConnectionConfig);
dbWrapper.connect();

一旦你开始工作,可能会想知道为什么 node-dbi 看起来如此 "fragile" 并使用另一个数据库包装器,例如 sequelize 如果你不想直接使用 pg.

它应该可以与

一起使用
var sequelize = new Sequelize(pgconf.uri, {})

根据http://docs.sequelizejs.com/en/latest/api/sequelize/