2015-06-21 131 views
0

因此我正在执行heroku页面上的'getting started'过程。heroku node.js教程 - 将env变量发送到其他js页面

通过克隆他们的教程回购,我决定添加我自己的index.htmlapp.js文件到他们已经为我创建的/public文件夹中。

目录如下:

node-getting-started repo folder 
| node_modules folder 
| public folder 
| | app.js 
| | index.html 
| index.js 
| package.json 
| Procfile 

package.jsonmainindex.js看起来像这样:

index.js

var express = require('express'); 
var app = express(); 

app.set('port', (process.env.PORT || 5000)); 
app.use(express.static(__dirname + '/public')); 

app.get('/', function(request, response) { 
    var obj = { ... }; 
    var secret_key = process.env.SECRET_KEY; 
    // what should i do here to send the variables above to my app.js file? 
    // response.send(secret_key) ??? 
}); 

app.listen(app.get('port'), function() { 
    console.log('Node app is running on port', app.get('port')); 
}); 

在这一点上,是什么我试图做的是在内发送我的app.js文件,所以我可以在那里使用它。

这是正确的方式去做这件事吗?有没有其他的(适当的?)方式发送到其他文件?

我基本上想要做同样的事情与环境变量,如在index.js设置var secret_key = process.env.SECRET_KEY并发送到app.js,以便我也可以在那里使用它。

有人可以向我解释我该如何去做这件事?

回答

0

假设您想让SECRET_KEY对用户隐藏,您无法将其发送给客户端。在这种情况下,您需要将需要密钥的功能移至服务器。

对于需要密钥的API请求,请求客户端请求到您的服务器,服务器将使用密钥向API请求。您将要修改app.get路线:

// '/api-request' will be the URI that the client uses 
// the callback will handle what the server does when it receives a request with this URI 
app.get('/api-request', function(req, res){ 

    request('API_URL' + process.env.SECRET_KEY, function(err, data) { 

    // send error to the client -- res.send exits the function and ends the request 
    if (err) res.send(err) 

    // send data to the client 
    res.send(data) 
    }) 
}) 

您的服务器将作为中间人的API,让你的钥匙未曝光并载到服务器。

在客户端上,请求将接收服务器通过res.send发回的任何数据。客户不知道有一个中间人参与。

// the browser is smart and knows that a leading/refers to the current domain 
request('/api-request', function(err, data) { 
    if (err) // handle error 

    // do stuff with the data 
    console.log(data) 
}) 

需要密钥的其他操作可以用类似的方式处理。您的服务器将需要一条路由,客户端将向其发送包含任何相关信息的请求,并且服务器将发送任何结果数据。

1

为了将不同的数据从服务器传递到正在查看的页面,您需要渲染它。这与提供静态文件不同。

Express支持不同的模板引擎,如Jade,EJS和Handlebars。这里有一个简单的例子,使用express-generator。首先通过运行

$ mkdir example 
$ cd example 
$ sudo npm install -g express-generator 
$ express -e 

然后在routes/index.js你可以找到呈现视图称为指数并将沿着一个标题相关的部分创建示例项目。

router.get('/', function(req, res, next) { 
    res.render('index', { title: 'Express' }); 
}); 

你的问题的下一部分是从你的HTML弄清楚HOWTO将数据传递给在<script>元素加载的app.js