M
M
Maxim Romashko2020-10-11 15:21:12
React
Maxim Romashko, 2020-10-11 15:21:12

How to add post data to fetch?

Hello, I send a POST request to the server like this

drawTable(store = 1) {
        fetch(this.state.data.pricesUrl + `?form_key=${FORM_KEY}`, {
            method: 'POST',
            mode: 'cors', // no-cors, *cors, same-origin
            cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
            credentials: 'same-origin', // include, *same-origin, omits
            redirect: 'follow', // manual, *follow, error
            referrerPolicy: 'no-referrer',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                store: store
            })
        })

When a request is made to the server, there are request data in the dev tools:
{"store": 1}
But when the server starts processing, it sees that this is a post request, but does not see any parameters.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DanilYuma, 2020-10-15
@md5inj

In your execution of the request on the server, you should accept data through

$post = file_get_contents('php://input');
// $post -> JSON строка

If you need to receive data via $_POST, then you need to pass the FormData object to the body parameter.
For example:
let formData = new FormData();
formData.append('store', store);
fetch(this.state.data.pricesUrl + `?form_key=${FORM_KEY}`, {
    method: 'POST',
    body: formData
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question