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);
}
};