2

how can I use async/await syntax to make a http post request ? I need to have a http post request, without using old style callback or promise, I want to use new es6 style for async operations, async/await . and also I prefer not to use any third party package.

const data = JSON.stringify({
    name: 'majid',
});

const options = {
    hostname: 'example.com',
    port: 443,
    path: '/api/v1/test',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'token': '32rt35y43t43t'
    }
};

try {
    const response = await https.request(options);

    console.log(response);

}
catch (error) {
    console.log(error);
}

I'm aware of above syntax but I don't know where to put my request post body. I'm using nodejs 10.10.

my question is marked as duplicate but I check the question which should solve mine, but no luck, the question doesn't say anything about post body.

thanks to @jfriend00 my problem is solved and here is my code :

import rp from 'request-promise';

exports.echoApi = async () => {

    const options = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        uri: 'https://example.com/echo',
        body: {
            name: 'majid'
        },
        json: true
    };


    try {
        return await rp(options);
    }
    catch (error) {
        console.log(error);
    }

};
Majid Abdolhosseini
  • 2,191
  • 4
  • 31
  • 59
  • Maybe https://stackoverflow.com/questions/46142289/cant-do-http-request-with-async-and-await or https://stackoverflow.com/questions/41470296/how-to-await-and-return-the-result-of-a-http-request-so-that-multiple-request helps. – lependu Nov 18 '18 at 17:22
  • Take a look at that: https://stackoverflow.com/questions/40537749/how-do-i-make-a-https-post-in-node-js-without-any-third-party-module – nikos fotiadis Nov 18 '18 at 17:40
  • I checked the link, It's providing anonymous function to request for success and fail, but I don't want to use callback function. – Majid Abdolhosseini Nov 18 '18 at 18:11
  • 1
    `await` works with promises so you need to use a function that returns a promise to work with `await`. `https.request` does not return a promise so it will not do anything useful with `await`. I would suggest using the `request-promise` library instead of `https.request()`. In addition to returning promises so it can be used with `await`, it also offers a number of useful features beyond `https.request()`. – jfriend00 Nov 18 '18 at 18:43
  • @jfriend00 thanks I'll check that out ! – Majid Abdolhosseini Nov 18 '18 at 19:11
  • I don't think this question is a duplicate of the post it is linked with. Furthermore I don't think using yet another lib should be the way to go. I had the same issue created my own wrapper function and made the result available on [pastebin](https://pastebin.com/embed_iframe/zGv306PQ) because I can't make it available on this post anymore – TheBay0r Jan 31 '19 at 09:46

0 Answers0