The requested file cannot be accessed using XMLHttpRequest.open url

Currently, I am in the process of learning about AJAX by following the MDN tutorial. However, I have encountered an issue with the first sample code provided to fetch test.html. Regardless of whether I use absolute or relative paths, my local server consistently responds with a 404 error. I have researched similar questions on stackoverflow, but none of the solutions seem to resolve my problem.

Sharing 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>

After attempting templates/test.html and moving test.html outside of the templates directory, I continue to receive a 404 error even though the URL shown in the console is

http://127.0.0.1:5000/templates/test.html
, which seems correct.

I suspect that there might be a misunderstanding on my part regarding URLs, servers, or it could be related to Flask?

As a reference, here is the content of app.py:

from flask import Flask, render_template

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

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

Answer №1

Attempting to make requests to test.html will result in an error because that route does not exist in your Python code. Currently, only the / route is defined, which renders the index.html template.

If you want users to be able to access various templates (e.g.

127.0.0.1:5000/templates/my-template.html
), you can create a new route as follows:

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

After setting up this route, making a request to /templates/test.html should now be successful:

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

By default, Flask looks for templates in the templates folder when using the render_template function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing a Javascript function post AJAX page loading

I'm not a coding expert, so I hope my question is still clear. Essentially, I have an index.php page with filters (by project, year, month) that send variables to filterData.php after clicking submit. These variables are then used in SQL statements t ...

Is it possible to implement pagination for API requests in a JavaScript and React environment?

I am currently working on an app that fetches data from a movie API and returns 20 items from page 1. I am now looking to implement pagination so that users can click a button to view more items from subsequent pages. Below is my current API call: export ...

Encountering error: Unknown flag '-p' when trying to execute yarn build:prod in Angular 6

For the past two days, I have been encountering a problem. After updating Angular from version 4 to 6, I am unable to generate a production build. Commands like yarn build and yarn dev are functioning properly. However, when I execute yarn build:prod, I re ...

In Ruby on Rails, Disqus Ajax is failing to associate different threads with different posts

In my Rails application, I have integrated Disqus Universal Code for the comment function. I am utilizing ajax remote => true function to display the content of my posts. Below is the Disqus code snippet: <div id="disqus_thread"></div> ...

Challenges encountered while developing Angular FormArrays: Managing value changes, applying validators, and resolving checkbox deselection

I am facing an issue with my Angular formArray of checkboxes. In order to ensure that at least one checkbox is selected, I have implemented a validator. However, there are two problems that I need to address: Firstly, when the last checkbox is selecte ...

Phaser 3 game app on iOS generated with Capacitor lacks audio functionality

I have developed a basic test app using Phaser 3 (written in Typescript and transpiled with rollup) and am utilizing Capacitor to convert it into an iOS application on my Mac. This excerpt highlights the key functionality of the app: function preload () { ...

What is the preferred approach: displaying a message using a service or a directive?

I'm feeling a bit unsure. I understand that anything interacting with the DOM should be created as a directive. However, I find it more convenient to simply call my notification service to display error or success messages. This service internally cr ...

Display markers on the canvas

I am having trouble painting points from a JSON object on canvas using the following code. Can someone help me identify where I went wrong? var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var t = [{"prevX":39,"prevY":58,"currX ...

Is it possible to incorporate both Matter and Arcade physics into the Player object?

I attempted to instantiate a player object export default class Player extends Phaser.Physics.Matter.Sprite { constructor(data) { let { scene, x, y, texture, frame } = data; super(scene.matter.world, x, y, texture, frame); this. ...

I'm having trouble with my TextGeometry not displaying on screen. Can someone help me figure

Here is the code I am using for Three.js: <html> <head> <title>My first Three.js app</title> <style> body { margin: 0; } canvas { width: 100%; height: 100% } </style> ...

Using AngularJS to send data from a controller to a factory

Looking to implement a basic pagination feature with data from the backend. Each page should display 10 activities. /feed/1 -> displays 0-10 /feed/2 -> displays 10-20 /feed/3 -> displays 20-30 The goal is to start at page 1 and increment the pag ...

Mastering the correct usage of the submitHandler method in the jQuery validation plugin

Here is a snippet of documentation from the jQuery validation plugin: "Use submitHandler to execute some code before submitting the form, without triggering the validation again." submitHandler: function(form) { $.ajax({ type: 'POST&apos ...

Deliver a response to recipients through the "button" feature within the WhatsApp cloud API

I'm working on building a chatbot for my booking company. Here is an outline of my initial bot flow: const axios = require("axios").default; function initialize_bot(message, phone_number, access_token, sender, username) { if (message === ...

Exploring JavaScript: Accessing an array object within another object

I'm having trouble accessing an array object within an object in JavaScript. The object structure is as follows: categories: Array(5) 0: name: "Electronics" subCategories: Array(16) 0: name: "Video Games & Accessories" __typena ...

Unable to utilize the .keyCode method within a query selector

Trying to utilize .keyCode in JavaScript to identify a pressed key, but the console consistently displays null after each key press. Below is the relevant CSS code: <audio data-key="65" src="sounds\crash.mp3"></audio> ...

jQuery toggle buttons to show or hide on radio button selection

I have a pair of buttons and a pair of radio buttons Buttons 1) btnErp 2) btngoogle Radio Buttons 1) rdiogoogle 2) rdioErp When I select 'rdiogoogle', 'btngoogle' should be visible while 'btnErp' should be hidden. Conve ...

Javascript - formatting numbers with decimals

This question is not related to math or operators, but rather a formatting or masking issue. I am working on creating an order form that uses Javascript to tally and display the quantity and cost of each column in separate fields. I am trying to format th ...

Converting objects into CSV format and exporting them using JavaScript

When exporting to CSV, large strings are causing other cells to be rewritten. See the screenshot for the result of the export here. For the code related to this issue, refer to this link. The question is how to prevent large string values in a cell from a ...

I keep encountering the issue where nothing seems to be accessible

I encountered an error while working on a project using React and Typescript. The error message reads: "export 'useTableProps' (reexported as 'useTableProps') was not found in './useTable' (possible exports: useTable)". It ...

Is there a way to access the HTML and CSS source code without using the inspect feature

I'm working on a project that involves an "edit box" where users can write text, add emojis, change the background color, insert images, and more. After users finish creating their content, I want them to be able to send it via email. This means I ne ...