Z
Z
zlodiak2018-07-11 22:41:19
JavaScript
zlodiak, 2018-07-11 22:41:19

Why xhr request fails?

I set up the ability to receive and write a cookie through a cross-domain request on the front and back. As a result, after the request leaves the front and returns with the 200 code, the cookie is written to the browser's storage.

But at the same time, the xhr request fails with an error. This is expressed in the fact that the xhr.onerror handler is fired. In this case, the xhr.onload handler does not work.

Please help me figure out why this is happening.

Here is the ajax request code:

const xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.open('GET', Config.host + 'users/display_form', true);
    xhr.onload = function() {
      alert( 'xhr req ok' );
    }
    xhr.onerror = function() {
      console.log( 'Ошибка ' + this);
      console.dir(this);
    }
    xhr.send();


Here is the controller code on the backend:
def display_form(request):
    response = HttpResponse('set csrf cookie for form')
    rotate_token(request)   # здесь генерируется свежая кука и помещается в соответствующий заголовок ответа
    response['Access-Control-Allow-Origin'] = 'http://localhost:4200'
    response['Access-Control-Allow-Credentials'] = 'true'
    response['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, X-CSRF-TOKEN'
    return response


Here are screenshots of the http debugger in the browser:
5b465cbc1dd93445223864.png
5b465cc17cd77810308054.png
5b465cc85004c640055631.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Kornilov, 2018-07-12
@zlodiak

It's all written. Server does not return php header('Access-Control-Allow-Origin: *')
Treatment - https://ru.stackoverflow.com/questions/482217/php-...

E
Eugene, 2018-07-11
@MrResilient

I did not particularly read the code, since the error in most cases is different. The default browser has protection against such requests, that is, if your request was executed from the host, then most likely everything would be ok. I know as many as 2 solutions, there are mb and more of them. The first is to install this extension https://chrome.google.com/webstore/detail/allow-co... (if you use chrome), and the second is to write the following lines in the browser configs --disable-web-security -- user-data-dir (in the properties, in the "object" field, separated by a space from what is already there)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question