K
K
khodos_dmitry2022-03-19 12:03:33
AJAX
khodos_dmitry, 2022-03-19 12:03:33

Why isn't data sent via post?

(function () {
    'use strict';
    setTimeout(() => {
        check();
    }, 3000);
})();

async function check() {
        try {
            const response = await fetch('https://site.ru/script.php', {
                method: 'POST',
                body: JSON.stringify({yes: 'yes'}),
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            console.log(response);
            const json = await response.json();

            console.log('Успех:', json);
        } catch (error) {
            console.error('Ошибка:', error);
        }
}

I want to send a request from another site with tempermonkey when I visit it.
It can be seen that the request is sent and the response comes back. But $_POST and $_REQUEST are empty.
CORS sort of allowed:
a2enmod headers
and in .htaccess
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control- Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
Send data screen:
6235d9cf7cc39743107217.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nadim Zakirov, 2022-03-19
@khodos_dmitry

To $_POSTbe NOT empty, you must send data in encoding application/x-www-form-urlencodedor multipart/form-data. In your example, you are trying to send data in encoding application/json, while doing it wrong.
Try like this:

window.addEventListener('load', check); // Запуск check после полной загрузки страницы

async function check() {
  
  var data = {
    'test': 'Привет, мир!',
    'myname': 'Дмитрий'
  };

  var response = await (await fetch('https://site.ru/script.php', {
    'method': 'POST',
    'headers': {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    'body': new URLSearchParams(data).toString()
  })).text();

  console.log('Ответ сервера:', response);
  
  return response;
  
}

A
AUser0, 2022-03-19
@AUser0

IMHO, you have text in 'body' that is not JSON at all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question