Dear gurus,
I have attached a screenshot. My goal is to use lambda and make a 3rd party website request to get token. The request header/body are correct as tested in postman. But when i migrate them to lambda code (as following, it failed)
const https = require('https');
function postRequest(body) {
const options = {
hostname: 'sea.bipocloud.com',
path: '/DEMOSEA/oauth2/webapi/token',
method: 'POST',
port: 443, // 👈️ replace with 80 for HTTP requests
headers: {
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
};
return new Promise((resolve, reject) => {
const req = https.request(options, res => {
let rawData = '';
res.on('data', chunk => {
rawData += chunk;
});
res.on('end', () => {
try {
resolve(JSON.parse(rawData));
} catch (err) {
reject(new Error(err));
}
});
});
req.on('error', err => {
reject(new Error(err));
});
// 👇️ write the body to the Request object
req.write(JSON.stringify(body));
req.end();
});
}
exports.handler = async event => {
try {
const result = await postRequest({
UserName: '...',
Password: '...',
grant_type: 'password',
client_id: '...',
client_secret: '...',
serviceConnection: '...',
});
console.log('result is: 👉️', result);
// 👇️️ response structure assume you use proxy integration with API gateway
return {
statusCode: 200,
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(result),
};
} catch (error) {
console.log('Error is: 👉️', error);
return {
statusCode: 400,
body: error.message,
};
}
};