Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask app can't find javascript file through relative path? [duplicate]

Tags:

flask

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 ?

like image 310
Hojas Avatar asked Sep 28 '22 23:09

Hojas


2 Answers

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.

like image 71
Ewan Avatar answered Oct 02 '22 16:10

Ewan


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

<script src="{% url_for('static', filename='js/main.js' %}"></script>
like image 32
dirn Avatar answered Oct 02 '22 14:10

dirn