D
D
Dmitry Mishutin2020-07-18 14:22:46
Node.js
Dmitry Mishutin, 2020-07-18 14:22:46

How to rewrite PHP POST request to Node js?

How to rewrite sending a given POST request from PHP to Node.js?

$params = [
    'method' => 'getSynText',
    'text' => 'Синонимизация текста совершенно бесплатно'
];
$ch = curl_init('https://rustxt.ru/api/index.php');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "X-Requested-With: XMLHttpRequest",
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch);
curl_close($ch);
$json_arr = json_decode($result, true);

print_r($json_arr);


I tried to do this, but it says undefined:
console.log(getPostResponse());

function getPostResponse() {
    request.post({
        url: 'https://rustxt.ru/api/index.php',
        form: {
            method: 'getSynText',
            text: 'Синонимизация текста совершенно бесплатно'
        }
    }, (err, response, body) => {
        if (err) {
            return err;
        }

        return body;
    });
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Silantiev, 2020-07-20
@MeShootIn

getPostResponse does not return anything in this case, here you need to use a promise for this, and call the function itself using async / await ...

(async () => {
    console.log(await getPostResponse());
})();

function getPostResponse() {
    return new Promise((resolve, reject) => {
    request.post({
        url: 'https://rustxt.ru/api/index.php',
        form: {
            method: 'getSynText',
            text: 'Синонимизация текста совершенно бесплатно'
        }
    }, (err, response, body) => {
        if (err) {
            return reject(err);
        }

        resolve(body);
    });
    });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question