Вызов API HTTPS REST из узла JS TypeError: первый аргумент должен быть строкой или буфером - PullRequest
0 голосов
/ 24 мая 2018

Я пытаюсь интегрировать API чата в приложении js узла. После получения ответа от чата я пытаюсь вызвать REST API (размещенный на сервере HTTPS), но он выдает следующую ошибку.Я думал, что есть некоторая проблема с запросом POST, поэтому я также попытался с запросом GET, но он выдает ту же ошибку.

Exception has occurred: TypeError
TypeError: **First argument must be a string or Buffer**
    at write_ (_http_outgoing.js:645:11)
    at ServerResponse.write (_http_outgoing.js:620:10)
    at IncomingMessage.<anonymous> (c:\Users\ChatBot.js:107:26)
    at emitOne (events.js:116:13)
    at IncomingMessage.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)
    at readableAddChunk (_stream_readable.js:250:11)
    at IncomingMessage.Readable.push (_stream_readable.js:208:10)
    at HTTPParser.parserOnBody (_http_common.js:141:22)

Ниже следует mychatbot.js код

const request = require('request');
const auth = require('basic-auth');
const url = require('url');
const http = require('http');

const port = '3008';
const botId = 'mychatbot@mrchatbots.com';
const secretKey = 'password1234';

if (!botId || !secretKey) {
    console.error(`Usage: <script> <port> <botId> <secret>`);
    process.exit(1);
}

// Start the express server
let app = startHttpServer();

registerBot(botId, secretKey, port)
    .then(() => {
        console.log('Chatbot registered and ready to receive messages...');
    })
    .catch(error => {
        console.error('Error registering chat bot:', error);
        process.exit(2);
    });

// Handle the message and generate the response
function getResponse(from, message) {
    if (message.indexOf('prod') > -1) {
        // Call the REST API to get information for requested product
        var messageArray = message.split(' ');
        return getProductData(messageArray[1]);
    } else {
        return `Hello <span style='color:blue;'>${from}</span>, you said: <span style='color:red;'>${message}</span>`;
    }
}

function getProductData(message) {
    var postURL = "https://myexample.com:8443/Products/SearchProduct";

    var query = "db.Products.find( { $and : [{ productID : '" + message + "' }, { recTime : {$lt : '2018-05-23T23:59:59Z' }}, { recTime : {$gt : '2018-05-22T23:59:59Z' }} ] },  {productID:1,productType:1,productCol:1 } ).sort({_id:-1}).limit(10)";


    /* Try with GET request
    request.get(
        'https://myexample.com:8443/Products/AllProduct',
        function (error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log(body)
            }
        }
    );
    */

    // Try with POST request
    request.post(
        'https://myexample.com:8443/Products/SearchProduct',
        { json: { query: query } },
        function (error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log(body)
            }
        }
    );
}

function startHttpServer() {
    const server = http.createServer((request, response) => {

        let message;
        // How to get the message body depends on the Method of the request
        if (request.method === 'POST') {
            var body = '';

            request.on('data', function (data) {
                body += data;
            });

            request.on('end', function () {
                 var post = JSON.parse(body);
                 response.writeHead(200);
                 response.write(getResponse(post.from, post.message), "UTF8");
                 response.end();
            });
        }
        else if (request.method === 'GET') {
            var p = url.parse(request.url, true);
            response.writeHead(200);
            response.write(getResponse(p.query.from, p.query.message), "UTF8");
            response.end();
        }
    });

    server.listen(Number(port));
    return server;
}

// Dynamically register the bot's URL on startup
function registerBot(id, secret, port) {
    return new Promise((resolve, reject) => {
        request
            .post('http://mrchatbots.com:19219/registerurl', {
                proxy: '',
                body: `http://auto:${port}`,
                headers: {
                    'Content-Type': 'text/plain'
                }
            })
            .auth(id, secret)
            .on('response', (response) => {
                if (response.statusCode !== 200) {
                    reject(response.statusMessage);
                    return;
                }
                resolve();
            });
    });
}

1 Ответ

0 голосов
/ 24 мая 2018

req.write() принимает либо string, либо Buffer, но вы передаете undefined

response.write(getResponse(post.from, post.message), "UTF8");

getResponse возвращает undefined при вызове getProductData, так какне имеет возвращаемого значения, и это асинхронная функция.

getProductData асинхронный, но вы рассматриваете его как синхронный.

Вы должны заключить request в Promise или используйте request-promise пакет.И тогда вы можете использовать async/await на вашем request.on('end') слушателе, чтобы дождаться окончания getProductData.

function getProductData(message) {
    var postURL = "https://myexample.com:8443/Products/SearchProduct";

    var query = "...";

    return new Promise((resolve, reject) => {

        request.post(
            'https://myexample.com:8443/Products/SearchProduct',
            { json: { query: query } },
            function (error, response, body) {
                if (!error && response.statusCode == 200) {
                    return resolve(body);
                }

                reject(error || body);
            }
        );

    });
}


function startHttpServer() {
    const server = http.createServer((request, response) => {

        let message;
        // How to get the message body depends on the Method of the request
        if (request.method === 'POST') {

            /* ... */
            request.on('end', async function () {
                              // ^^ notice async
                 var post = JSON.parse(body);
                 response.writeHead(200);
                 response.write(await getResponse(post.from, post.message), "UTF8");
                 response.end();
            });
        }

        /* ... */
        // Do the same for GET requests
    });

    server.listen(Number(port));
    return server;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...