admin管理员组文章数量:1394056
So I have django project with jquery for interactivity in frontend. I already have .env file to store database configuration to be used by django settings.py, but I need jquery to be able to access the .env file too.
From what I read in dotenv documentation, I need to install the dotenv using npm or yarn. But I think jquery don't have/use npm? I am a newbie in javascript
So I have django project with jquery for interactivity in frontend. I already have .env file to store database configuration to be used by django settings.py, but I need jquery to be able to access the .env file too.
From what I read in dotenv documentation, I need to install the dotenv using npm or yarn. But I think jquery don't have/use npm? I am a newbie in javascript
Share asked Sep 30, 2019 at 11:38 cainamcainam 751 silver badge6 bronze badges 2- That's impossible. Javascript/jquery is running on the frontend, i.e. in the browser of your users. The .env you're talking about is on the server running Django. What exactly are you trying to achieve? – dirkgroten Commented Sep 30, 2019 at 11:43
- @dirkgroten I want to store the hostname in the .env file. I use jquery to hit API from the django rest framework. The problem is when running in local I use "localhost" and when I deploy the code it needs to use different url/host. – cainam Commented Sep 30, 2019 at 11:48
1 Answer
Reset to default 5Your script can't have access to .env, since it's running in your users' browsers.
First, if your API is hosted on the same domain as your page itself, you don't need to specify a hostname, just use relative URLs ('/api/v1/path/to/resource/'). That way your script doesn't need to know the host. Also, in Javascript, document.location
will give you all the information about the current host.
Second, if it's not the same or you want other URL parameters to be set by Django for your script to use, set a variable in your template using a context variable. E.g. if your view fetches settings.API_URL
and passes it as api_url
to the context, you can do this in your template:
<script>var APIUrl = "{{ api_url }}"</script>
Then, as long as your jQuery script runs after this variable was defined, it will have access to it.
本文标签: javascriptHow to access env file in jqueryStack Overflow
版权声明:本文标题:javascript - How to access .env file in jquery? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744650461a2617653.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论