5

In my Flask app. If the page's path is http://example.com/product/6. I can't import js file in this page's html file like this :

<script src="js/main.js"></script>

The browser will search the js file in http://example.com.product/js/main.js, and return 404 error.

So, what should I do to fix this ?

Hojas
  • 51
  • 1
  • 1
  • 3

2 Answers2

3

You should use url_for to generate the URLs for your static assets.

<script src="{% url_for('static', filename='js/main.js' %}"></script>
dirn
  • 19,454
  • 5
  • 69
  • 74
  • You asked about getting the JavaScript files to load. You should use `url_for` for that. If you want to know how to reference URLs inside JavaScript files, that is a completely different question that can be answered either by placing the URLs in JavaScript inside a template file or by placing the URLs directly into the JavaScript files. – dirn Jan 20 '15 at 01:44
2

You should make your static resources use the root directory (if that's where you're keeping them all).

So if your directory looks like this:

.
├── app.py
└── static
    ├── css
    ├── img
    └── js
        └── main.js

try adding a / onto your javascript URL so it isn't just appended onto the page URL.

e.g. <script src="js/main.js"></script> will then go to http://example.com/js/main.js.

FYI - You should be using a web server such as apache or nginx to server your static files as they are a lot better at it than Flask.

Ewan
  • 14,592
  • 6
  • 48
  • 62
  • 1
    Can you elaborate on why Apache or Nginx are a lot better than Flask? In what way? – zwep Apr 03 '18 at 06:55
  • 2
    @zwep I actually wrote a bit more information [in a different answer](https://stackoverflow.com/a/20213086/1401034) but basically for performance (Flask only serves one request at a time) and security are the top priorities. They are specifically designed to handle more traffic and be configurable for things like SSL termination. – Ewan Apr 03 '18 at 10:07