Change jQuery ajax POJ request to choose api POST

I have some json data that I sent to the API using $ .ajax, but I would like to update it to use the fetch API. However, it seems to me that he set up the Fetch API request, ending with a 403 return, so I need to miss something, but I cannot process it.

Ajax request:

$.ajax({
        type: 'POST',
        url: url,
        data: {
            'title': data.title,
            'body': data.body,
            'csrfmiddlewaretoken': csrf_token,
            'request_json': true
        },
        success: function (data) {
            console.log(data)
        }
    });

retrieval attempt (one of many):

let payload = {
    'title': data.title,
    'body': data.body,
    'csrfmiddlewaretoken': csrf_token,
    'request_json': true
}

let request = new Request(url, {
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body:  JSON.stringify( payload )
});

fetch(request)
        .then((response) => {
            if (!response.ok) {
                throw Error(response.statusText);
            }
            return response;
        })
        .then((response) => response.json())

I tried with various headers, encoding the content and submitting the data as form data using:

let form_data = new FormData();
form_data.append( "json", JSON.stringify( payload ) );

let request = new Request(url, {
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body:  form_data
});
...

Any help would be great and if you need more info let me know

thank

+1
source share
2 answers

jQuery.ajax , , jQuery cookie , fetch .

MDN ( ):

, jQuery.ajax() , :
- , fetch(), HTTP- [...]
- cookie , , ( cookie, ).

, 403 (Forbidden), API, , cookie / ( , a csrfmiddlewaretoken, - cookie - Django?).

, credentials: "same-origin" Request (*), :

let request = new Request(url, {
    method: 'post',
    credentials: 'same-origin',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(payload)
});

(*) credentials :

  • omit: cookie. ( ).
  • same-origin: cookie, URL- script.
  • include: cookie, .
+2

:

'Content-Type': 'application/x-www-form-urlencoded'

 body:  JSON.stringify( payload )

JSON - , WWW!


form_data.append( "json", JSON.stringify( payload ) );

FormData Multipart MIME.

Multipart MIME WWW.

JSON Multipart MIME .


, (payload) .

0

Source: https://habr.com/ru/post/1679935/


All Articles