1

I am trying to build my first Single Page Application following a tutorial but I cannot load the local javascript file.

My Python code:

from flask import Flask, current_app


app = Flask(__name__, static_folder='')

@app.route('/')
def index():
    return current_app.send_static_file('index.html')

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

My HTML:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title>My Page</title>
    <script
    src="https://code.jquery.com/jquery-3.4.0.min.js"
    integrity="sha256-BJeo0qm959uMBGb65z40ejJYGSgR7REI4+CW1fNKwOg="
    crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body>

    <div ng-controller="IndexController">
        <p>{{message}}</p>
    </div>


    <script src="./static/js/app.js"></script>
</body>
</html>

My JavaScript:

var myApp = angular.module('myApp', []);

myApp.controller('IndexController', function($scope){
    $scope.message = 'binded ok';
});

The folder structure is:

MyApp
 |-static
 | |-js
 |   |-app.js
 |-index.html
 |-server.py

Everything loads okay except for app.js that gives me:

Request URL: http://localhost:5000/static/js/app.js

Status Code: 404 NOT FOUND

EDIT: If I open index.html directly using the browser app.js is loaded. So I think that Flask is creating an issue here.

3
  • Related: stackoverflow.com/questions/20646822/… Commented Apr 15, 2019 at 9:33
  • you should load script as ../../static/js/app.js Commented Apr 15, 2019 at 9:43
  • @Yuri it doesn't work. Same behavior. Commented Apr 15, 2019 at 9:48

2 Answers 2

1

Try referencing your JS file like so:

<script src="{{ url_for('static', filename='static/js/app.js') }}"></script>

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

6 Comments

Doesn't work. 404 Not Found once again, with different path.
Ah, right, I see, sorry. Problem here is that you are serving your index.html as a static file rather than as a template. I'm not sure it you'll be able to refer to your JS file that way.
So what changes would you recommend in my server.py?
Something like this.
I don't want it to be treated with jinja. Tried to use send_file() but same problem.
|
0

Create your App with app = Flask(__name__, static_folder='', static_url_path='')

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.