A
A
Alexey Segodin2018-10-16 13:34:07
JavaScript
Alexey Segodin, 2018-10-16 13:34:07

XHR works, fetch doesn't. There are no visible differences in query parameters. What is the problem?

Hey!
Help, please, with a problem. I don't know what's the matter.
There is a code that works fine:

let formData = new FormData();
formData.append('x', x);
formData.append('y', y);
            
var xhr = new XMLHttpRequest();        
xhr.open('POST', `/team/${id}`);
xhr.setRequestHeader('X-CSRF-TOKEN', token);
xhr.send(formData);

But when I change it to a similar fetch, the server returns a 500 error:
let formData = new FormData();
formData.append('x', x);
formData.append('y', y);

fetch(`/team/${id}`,
    {
        method: 'POST',
        headers : {
            'X-XSRF-TOKEN': token
        },
        body: formData
});

On the server, the data is received by Laravel . Bekender says that in the case of fetch , the data does not seem to reach Laravel - there is nothing to process. This is how the text of the error looks like:
5bc5bda5d0d4d188207963.png
And this is how requests through XHR and fetch look like :
5bc5bdc282351747640425.png5bc5bdc955fae465820101.png
Help me figure it out.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
My joy, 2018-10-16
@Aleksei_Segodin

in your example xhr: X-CSRF-TOKEN
and in the example with fetch: X - XSRF -TOKEN

M
Mikhail Osher, 2018-10-16
@miraage

In the first case, Content-Type = application/json, in the second - multipart/form-data.
Perhaps because of this problem. If you are not sending any files, then you need to change this header.
Using FormData forces the Content-Type=multipart/form-data header.
You can write const data = new URLSearchParams(formDataObject);
// EDIT
I ​​read the screenshots wrong, in both cases content-type=multipart/form-data flies away.. I guess
:)

F
frees2, 2018-10-16
@frees2

1 Heading, stupidly look at the samples.
2 The coolest thing is that js does not work on the side of the "loading page" (if any, in the case of fetch on the main one), this is done for security.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question