NodeJS 12.x https версия запроса curl на AWS Lambda - PullRequest
0 голосов
/ 24 февраля 2020
    curl -d "m_payment_id=m_payment_id-xxxxxxxxxxxxxxxxxyyy&pf_payment_id=990396&payment_status=COMPLETE&item_name=Subscription&item_description=Monthly+Subscription&amount_gross=99.00&amount_fee=-6.74&amount_net=92.26&custom_str1=&custom_str2=&custom_str3=&custom_str4=&custom_str5=&custom_int1=&custom_int2=&custom_int3=&custom_int4=&custom_int5=&name_first=&name_last=&email_address=christo%40g4-ape.co.za&merchant_id=0000000&token=0000000-0000-0000-3a83-25bc733a307b&billing_date=2020-02-21&signature=3895d0769b56862b842da5067af4483f" -X POST https://sandbox.somedomain.co.za/what/something/validate

Моя попытка:

const https = require("https");
const querystring = "m_payment_id=m_payment_id-xxxxxxxxxxxxxxxxxyyy&pf_payment_id=990396&payment_status=COMPLETE&item_name=Subscription&item_description=Monthly+Subscription&amount_gross=99.00&amount_fee=-6.74&amount_net=92.26&custom_str1=&custom_str2=&custom_str3=&custom_str4=&custom_str5=&custom_int1=&custom_int2=&custom_int3=&custom_int4=&custom_int5=&name_first=&name_last=&email_address=christo%40g4-ape.co.za&merchant_id=0000000&token=0000000-0000-0000-3a83-25bc733a307b&billing_date=2020-02-21&signature=3895d0769b56862b842da5067af4483f";

return new Promise((resolve, reject) => {
        const options = {
            hostname: 'sandbox.somedomain.co.za',
            port: 443,
            path: 'what/something/validate',
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': Buffer.byteLength(querystring)
            }
        };

        const req = https.request(options, (res) => {
            console.log('statusCode: ' + res.statusCode);
            console.log('headers: ' + JSON.stringify(res.headers));
            res.setEncoding('utf8');

            let data = '';
            res.on('data', (chunk) => {
                data += chunk;
            });
            res.on('end', () => {
                console.log('BODY: ' + data);
            });

            resolve('Success');
        });

        req.on('error', (e) => {
            console.log('problem with request: ' + e.message);
            reject(e.message);
        });

        // write data to request body
        req.write(querystring);
        req.end();
    });

Я продолжаю получать код состояния 400 по коду NodeJS, скручивание работает нормально. Очевидно, имя хоста было изменено для безопасности.

Может кто-нибудь посоветовать мне, что я здесь делаю неправильно?

1 Ответ

0 голосов
/ 24 февраля 2020

Content-Length требуется, когда вы отправляете тело во время публикации. В вашем случае вся информация передается как параметр строки запроса, так что вы можете полностью избавиться от заголовков.

Кроме того, вы должны разрешить внутри res.on('end'. То, как вы это делаете, завершит sh функцию до того, как она завершит выполнение.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...