Raykie
Raykie

Reputation: 31

XMLHttpRequest.open url can't access the file I request for

I'm learning AJAX according to MDN tutorial, but when I try the first sample to fetch test.html, local server always response with 404, no matter I use absolute or relative path. I have read other similar questions in stackoverflow, but none of them can solve my problem.

Here is my directory structure and source code:

|--templates
|  |--index.html
|  |--test.html
|
|--app.py

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>index</title>
  </head>
  <body>
    <button id="ajaxButton" type="button">Make a request</button>
    <script>
      (function(){
          let httpRequest
          document.getElementById("ajaxButton").addEventListener('click', makeRequest)

          function makeRequest() {
              httpRequest = new XMLHttpRequest()

              if (!httpRequest) {
                  alert('Giving up: can not create an XMLHTTP instance')
                  return false
              }

              httpRequest.onreadystatechange = alertContents
              httpRequest.open('GET', 'test.html', true)
              httpRequest.send()
          }

          function alertContents() {
            if (httpRequest.readyState === XMLHttpRequest.DONE) {
                if (httpRequest.status === 200) {
                    alert(httpRequest.responseText)
                }else {
                    alert('There was a problem with the request.')
                }
            }
          }
      })();
    </script>
  </body>
</html>

I have tried templates/test.html or put test.html outside templates directory but it always return 404 even though I find the url in console is http://127.0.0.1:5000/templates/test.html, which should be right.

I think I must misunderstand someting about URL and server or it matters with flask?

Just in case, here is app.py:

from flask import Flask, render_template

app = Flask(
    __name__,
    template_folder='./templates'
)

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

Upvotes: 0

Views: 1298

Answers (1)

vremes
vremes

Reputation: 674

You're trying to do requests to test.html, but that route does not exist, you have only defined the / route in your Python code which renders index.html template.

If you want the user to access arbitrary templates (e.g. 127.0.0.1:5000/templates/my-template.html), you can write the following route:

@app.route('/templates/<template_name>')
def view_template(template_name):
    return render_template(template_name)

Once you've defined that route, the request to /templates/test.html should be successful:

httpRequest.open('GET', '/templates/test.html', true)

Flask looks for the specified template in templates folder by default when you call render_template.

Upvotes: 1

Related Questions