Appfog与node.js如何访问与JavaScript到MySQL数据库?

我有一个node.js应用程序发布在appfog中,但是当我尝试通过javascript( https://github.com/felixge/node-mysql )访问mysql数据库时,“node-mysql”似乎没有安装,有什么办法做到这一点? appfog网站上没有任何文档。 谢谢。

服务器app.js的代码:

if(process.env.VCAP_SERVICES){ var env = JSON.parse(process.env.VCAP_SERVICES); var cre = env['mysql-5.1'][0]['credentials']; } var Client = require('mysql').Client, client = new Client(); client.user = cre.user; client.password = cre.password; client.host=cre.host; client.port=cre.port; client.database=cre.name; client.connect(); client.query( 'SELECT * FROM scores ', function selectPlayers(err, results, fields) { if (err) { console.log("Error: " + err.message); throw err; } console.log("Number of rows: "+results.length); console.log(results); client.end(); }); 

和错误:

 module.js:340 throw err; ^ Error: Cannot find module 'mysql' at Function.Module._resolveFilename (module.js:338:15) 

你应该添加

 "mysql": "2.0.x || 2.1.x", 

到package.json文件中的依赖关系,然后执行

 npm install 

你可以在这里查看Appfog的文档 。 有一个关于依赖pipe理的部分

Appfog支持NPM,这是在节点中安装依赖关系的标准方式。

您可以通过控制台使用npm install mysql或者将mysql添加到您的package.json文件并执行npm install

第二种方式将自动安装您的应用程序的所有依赖项。

来源: https : //docs.appfog.com/languages/node#node-dep-mgmt

您好,您只需要在本地下载并安装node.js,然后在您的AppFog面板上的“Services”部分创build您的mySQL服务(VCAP_SERVICES),然后在您的机器上启用npm命令。

当您提供服务并将其绑定到应用程序时,AppFog会创build一个名为VCAP_SERVICES的环境variables。

此variables包含一个JSON文档,其中包含绑定服务的所有凭证和连接信息的列表。

下面是一个有两个MySQL数据库服务绑定到的应用程序环境variables的例子:

 {"mysql-5.1":[ { "name":"mysql-4f700", "label":"mysql-5.1", "plan":"free", "tags":["mysql","mysql-5.1","relational"], "credentials":{ "name":"d6d665aa69817406d8901cd145e05e3c6", "hostname":"mysql-node01.us-east-1.aws.af.cm", "host":"mysql-node01.us-east-1.aws.af.cm", "port":3306, "user":"uB7CoL4Hxv9Ny", "username":"uB7CoL4Hxv9Ny", "password":"pzAx0iaOp2yKB" } }, { "name":"mysql-f1a13", "label":"mysql-5.1", "plan":"free", "tags":["mysql","mysql-5.1","relational"], "credentials":{ "name":"db777ab9da32047d99dd6cdae3aafebda", "hostname":"mysql-node01.us-east-1.aws.af.cm", "host":"mysql-node01.us-east-1.aws.af.cm", "port":3306, "user":"uJHApvZF6JBqT", "username":"uJHApvZF6JBqT", "password":"p146KmfkqGYmi" } } ]} 

您可以使用应用程序的特定于语言的工具来调用环境variables。

在Java中:

  java.lang.System.getenv("VCAP_SERVICES") 

在Ruby中:

  ENV['VCAP_SERVICES'] 

在Javascript中:

  process.env.VCAP_SERVICES 

在Python中:

  os.getenv("VCAP_SERVICES") 

在PHP中:

  getenv("VCAP_SERVICES")