Search code examples
node.jsrequestremote-serverrequest-promiseremote-host

NodeJS - ERR_INVALID_ARG_TYPE Error thrown while issuing a HTTP request to remote host


Recently, I encountered a problem while trying to issue a request using NodeJS and request-promise.

The following code is nested inside a multer call for file uploading (using nested functions / clusters.

    const options = {
        method: 'POST',
        uri: 'URL of your choice',
        body: {
            //Body of the request
        },
        // json: true,
        headers: {
            // 'Content-Type': 'application/x-www-form-urlencoded',
        },
    }

    request(options)
        .then(function (response) {
            console.log('Response: ', response);

        })
        .catch(function (err) {
            console.log('Error: ', err);
        });

While using the current request, without the 'json: true' property (commented out), I get the following error:

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string or Buffer. Received type object
    at write_ (_http_outgoing.js:603:11)
    at ClientRequest.write (_http_outgoing.js:575:10)
    at Request.write (PATH/node_modules/request/request.js:1500:27)
    at end (PATH/node_modules/request/request.js:549:18)
    at Immediate.<anonymous> (PATH/node_modules/request/request.js:578:7)
    at runCallback (timers.js:696:18)
    at tryOnImmediate (timers.js:667:5)
    at processImmediate (timers.js:649:5)
    at process.topLevelDomainCallback (domain.js:121:23)

And when I turn the 'json: true' option on, the problem doesn't occur, but the remote API returns an error as it doesn't handle JSON requests/their added curly braces well.

Any ideas about getting over this issue?

Thank you.


Solution

  • Solved it!
    As the remote host doesn't handle JSON well, and required "ordinary" POST request to be sent, I looked again inside request-promise's documentation. By changing body{} to formData{}, and commenting out json: true, the problem was solved.

    const options = {
        method: 'POST',
        uri: 'URL of your choice',
        formData: {
            //Request's data
        },
    }
    
    request(options)
        .then(function (response) {
            console.log('Response: ', response);
    
        })
        .catch(function (err) {
            console.log('Error: ', err);
        });