0

I have the following Flask app, and I am trying to load a js file from a template:

from flask import Flask, request, send_from_directory, render_template

# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='')

@app.route('/js/<path:path>')
def send_js(path):
    return send_from_directory('js', path)

@app.route("/")
def main():
    return render_template('index.html')

if __name__ == "__main__":
    app.run()

Here is the folder:

enter image description here

My index.html file does load but the js doesn't:

<head>
    <script src="/static/js/asynckittens.js"></script>
</head>



  hello world

I have tried it as /js/asynckittens.js, and even /asynckittens.js and nothing will load this file. How can I load a js file in a basic flask server?

4
  • Did you get any error? Commented Feb 26, 2021 at 2:21
  • Loading failed for the <script> with source “127.0.0.1:5000/js/asynckittens.js”. Commented Feb 26, 2021 at 2:22
  • 1
    Does this answer your question? How to serve static files in Flask Commented Feb 26, 2021 at 13:44
  • no thats the link i'm using it isn't working Commented Feb 26, 2021 at 15:28

1 Answer 1

2

For some reason, I had to delete the route serving js for flask to find these files:

@app.route('/js/<path:path>')
def send_js(path):
    return send_from_directory('js', path)

I'm not sure why deleting that made it work but it did

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.