[英]How to retrieve API key safely from .env file into javascript View - Laravel
I have the key placed safely in .env file and I would like to make an ajax request to a paid API service. 我已将密钥安全地放置在.env文件中,我想向付费API服务提出ajax请求。 I have the Javascript file (containing ajax code) which is in public/ajax.js
我有位于public / ajax.js中的Javascript文件(包含Ajax代码)
I can retrieve in this way, put this line of code : $key = env('SECRET_API_KEY');
我可以通过这种方式进行检索,将以下代码行放入:
$key = env('SECRET_API_KEY');
in controller and pass it to javascript directly using https://github.com/laracasts/PHP-Vars-To-Js-Transformer but then I am forced to put @include('footer')
in some X page. 在控制器中,并使用https://github.com/laracasts/PHP-Vars-To-Js-Transformer将其直接传递给javascript,但随后我被迫在某些X页面中放置
@include('footer')
。 So, when I check the source I see my API key :/ 因此,当我检查源代码时,我会看到我的API密钥:/
I am able to pull the data successfully but How to prevent this? 我能够成功提取数据,但是如何防止这种情况?
my current url : url:"http://johndoe?param1=abc¶m2=def&_token="+key,
in Ajax code. 我当前的网址:
url:"http://johndoe?param1=abc¶m2=def&_token="+key,
以Ajax代码表示。
If I directly put this in javascript $key = env('SECRET_API_KEY');
如果我直接将其放入javascript
$key = env('SECRET_API_KEY');
I get an error Uncaught ReferenceError: env is not defined
我收到错误
Uncaught ReferenceError: env is not defined
What is the best approach to retrieve api key? 检索api密钥的最佳方法是什么?
Define a route that your JS will call, from that route, define a controller and function that will handle the request and make the API call to the paid service. 定义一个您的JS将调用的路由,从该路由定义一个控制器和函数,该控制器和函数将处理请求并向付费服务进行API调用。
Route::get('api-call', 'APIController@call');
//APIController
//use GuzzleHttp\Exception\GuzzleException;
//use GuzzleHttp\Client;
...
public function call(Request $request)
{
$params = $request->all();
$api_key = env('SECRET_API_KEY');
$url = 'url-to-paid-service?' . $params . '&key=' . $api_key;
$client = new Client();
$res = $client->get($url);
return response()->json($res->getBody());
}
From your ajax, make the call http://your-own-site/api-call
在您的Ajax中,拨打电话
http://your-own-site/api-call
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.