Re: [whatwg/fetch] Request with GET/HEAD method cannot have body. (#551)

I agreed with the fact that it is not really a standard way and `fetch` should not support it. For my case, I kind of need to get it done as an interim solution while 3rd party provider is making a change on their API. So I want to share the solution that I went with using node `http` module in case someone else is in the same situation as me.

```javascript
import https from 'https';
import http from 'http';

const requestWithBody = (body, options = {}) => {
    return new Promise((resolve, reject) => {
        const callback = function (response) {
            let str = '';
            response.on('data', function (chunk) {
                str += chunk;
            });
            response.on('end', function () {
                resolve(JSON.parse(str));
            });
        };

        const req = (options.protocol === 'https:' ? https : http).request(options, callback);
        req.on('error', (e) => {
            reject(e);
        });
        req.write(body);
        req.end();
    });
};

// API call in async function
const body = JSON.stringify({ a: 1});
const result = await requestWithBody(body, options = {
        host: 'localhost',
        port: '3000',
        protocol: 'http:', // or 'https:'
        path: '/path',
        method: 'GET',
        headers: {
            'content-type': 'application/json',
            'Content-Length': body.length
        }
    };
)

```

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/fetch/issues/551#issuecomment-655848415

Received on Thursday, 9 July 2020 01:53:06 UTC