2015-06-21 63 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

相關問題