There is an absence of the 'Access-Control-Allow-Origin' header on the requested resource despite its existence

Currently, I am working on developing an application using Django and Phonegap. While attempting to send an Ajax Request with the following function:

<script>
            $.ajax({
                url: "http://192.168.0.101/commerce/product/" + localStorage.getItem("toView"),
                type: "GET",
                data: {},
        
                success: function (json) {
        
                    console.log(json);
        
                }
        
            });
        </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Upon executing this code, an error is displayed in the Chrome console:

XMLHttpRequest cannot load . Redirect from '' to '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access.

The issue seems to be related to missing or incorrect headers being included. Upon checking the URL in chrome and reviewing the server response, it appears as follows:

HTTP/1.0 200 OK
Date: Tue, 16 May 2017 09:42:29 GMT
Server: WSGIServer/0.2 CPython/3.4.3
Content-Type: application/json
Access-Control-Allow-Origin: *
X-Frame-Options: SAMEORIGIN
Access-Control-Allow-Methods: OPTIONS,GET,PUT,POST,DELETE
Access-Control-Allow-Headers: X-Requested-With, Content-Type
Content-Length: 89

In addition to providing insight into my server code located in views.py:

def product(request, prod_id):

    #### SOME CODE

    response = JsonResponse(response_data)
    response['Access-Control-Allow-Origin'] = '*'
    response['Access-Control-Allow-Methods'] = 'OPTIONS,GET,PUT,POST,DELETE'
    response['Access-Control-Allow-Headers'] = 'X-Requested-With, Content-Type'

    return response

I am uncertain about why this error persists. Any guidance would be greatly appreciated. Thank you.

Answer №1

It is recommended to include a forward slash at the end of the URL when making an ajax request:

url: "http://localhost/api/resource/" + sessionStorage.getItem("id") + '/',

The Django framework requires that URLs have a trailing slash.

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

"Encountering an 'Undefined function' error while implementing AJAX in the code

I'm encountering the issue Uncaught ReferenceError: GetLicenceUserList is not defined in the browser console when I utilize the function with $.ajax inside. However, the function works perfectly fine when I invoke it with just an alert("example& ...

Using jQuery to toggle sliding the information above a div

I am facing an issue with my customized sliding menu. The menu slides over the image but not over the content-div, pushing it aside. I have tried to fix this problem but haven't found a solution yet. My goal is for the menu to slide over all divs and ...

"Troubleshooting a glitch encountered while making an invokeAPI call with Azure Mobile

Working on integrating my Angular App with Azure Services as the back end. Initially, I used the standard $http call: $http({ method: 'POST', url: "https://services.example.com/Api/myApi", headers : { "Content-Type" ...

What is the best way to showcase the information from this API on an HTML page using Vanilla JavaScript?

I am currently working on implementing an AJAX call to fetch data from a movie API online. Below is the HTML code I have written for this: <html> <head> <meta charset=utf-8> <title>Movie Database</title> ...

Axios failing to transmit cookie information, despite setting withCredentials to true

Exploring the capabilities of React and Express to handle requests while including cookies. The communication between client-side and server-side is successful, however, the cookies are not being transmitted. On the client-side: import axios from 'axi ...

Ways to send information from Vue instance to nested components

Currently, I am fetching data using AJAX from the Vue instance and trying to pass it onto different components. As I delve deeper into learning Vue.js, I can't help but notice that the documentation seems a bit scattered... This snippet showcases wha ...

Send the form to the webpage and display various div elements based on the entered information

I have created a form that is designed to display one of four hidden divs on a page, depending on the input provided. Here is the form: <form> <input id="place" name="place" type="text"> <input name="datepicker" type="text" id="datepicker" ...

Quickest method for deriving a boolean value from multiple boolean inputs

Within a document, the keys isOccupied and vacant are being destructured. const { isOccupied, vacant } = doc || {}; boolDetermination = (isOccupied, vacant) => { if (isOccupied && isOccupied === vacant) { < --- Return isOccupied value ...

How can Ext JS 6.2 automatically expand the East panel when the West panel is triggered?

In my Ext JS v6.2 Grid application, I am faced with the task of ensuring that if the WestRegion panel is closed, the EastRegion panel should open automatically, and vice-versa. Being new to Ext JS, I initially attempted to achieve this using jQuery. Howeve ...

Unclear outcomes from iterative loops

I have a question about this particular for loop: for (var i=0,j=0;i<4,j<20;i++,j++) { a=i+j; } console.log(a); Can someone explain why the output is 38? I initially expected it to be 6. ...

Struggling to make comparisons with numerical data from MongoDB in an ExpressJS route

I am currently developing a website using Node.js, EJS template, MongoDB, and Express. I am working on implementing search functionality on my page using forms, but I am encountering a small issue. The problem is related to a logical issue in the search f ...

`Trick Ajax into displaying 200 status code even on error responses`

Is it possible to suppress exceptions in the console by manually setting the status code to 200 for all errors? For example, can I change a 500 internal server error response to 200? Although I understand that hard-coding status codes is generally conside ...

Building forms within an AngularJS directive

I recently developed an AngularJS directive that includes a form. This form consists of a required text field along with two additional child forms. Each child form also contains a required text field. The distinguishing factor between the two child forms ...

What is the best way to retrieve environment variables from an NPM package in an Angular 5 application

Is there a method for my node module, created from an Angular 5 application, to access the environment variable from the Angular 5 application (environments/environment.ts)? Perhaps Angular 5 exports its environment variables to JavaScript global variables ...

Ways to troubleshoot and fix the problem of encountering an "Internal Server Error" when sending emails with nodeMailer in node.js

When attempting to send a confirmation email using nodemailer, I encountered an internet server error in production when allowing insecure apps for Gmail accounts, although it works fine locally. Any suggestions on how to resolve this issue? router.post(& ...

Encounter a Socket.io connection error due to net::ERR_CONNECTION_REFUSED when trying to access from multiple devices

I'm having trouble with other people's computers accessing my test chatting application. When they try to connect, they encounter this error: localhost:3000/socket.io/?EIO=4&transport=polling&t=Oi2Ko0C:1 Failed to ...

Navigate to the AngularJS documentation and locate the section on monitoring data changes after a dropdown selection

Just starting out with AngularJS and Stack Overflow, so I hope I am asking this question correctly. I am working on a single-page application with editable text inputs. Two select drop-downs are used to control which data is displayed - one for time perio ...

JavaScript TypeError - missing method issue

When I try to call this code, I am encountering a TypeError: player = new Player({name:''}); Player = MeteorModel.extend({ schema:{ name:{type:String,}, value:{} }, belongsTo:{ meteorCollection:'', methodName ...

Is Cookie-session the most ideal choice for React applications?

My NodeJS application currently authenticates users through a third-party app. Once the app retrieves user data, a cookie is generated and sent to the client for React to access the user data from that Cookie. Should I stick with using cookies or consi ...

Controller using the 'as' syntax fails to add new object to array

Lately, I've been experimenting with the Controller as syntax in Angular. However, I seem to be struggling to grasp its functionality. I am currently following a tutorial that utilizes $scope to bind the members of the controller function rather than ...