所以我正在做heroku页面上的“入门”。
通过克隆他们的教程存储库,我决定将自己的文件index.html
和app.js
文件添加到/public
他们已经为我创建的文件夹中。
目录看起来像这样:
node-getting-started repo folder
| node_modules folder
| public folder
| | app.js
| | index.html
| index.js
| package.json
| Procfile
对package.json
的main
点,index.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'));
});
在这一点上,我想要做的是发送obj
内index.js
到我的app.js
文件,这样我就可以使用它。
这是解决这个问题的正确方法吗?是否有其他方法(正确吗?)将其发送到其他文件?
我想基本上要做环境变量,如设置同样的事情var secret_key = process.env.SECRET_KEY
在index.js
它发送到app.js
这样我可以有也使用它。
有人可以向我解释我该怎么做吗?
假设您希望对用户隐藏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)
})
需要键的其他操作可以类似的方式处理。您的服务器需要一条路由,客户端将向该路由发送包含任何相关信息的请求,并且服务器将发送任何结果数据。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句