node.jsaws-lambdahttp-postrequestjs

Always get 502 error when calling AWS lambda endpoint from Node Js using `requestjs`


trying to post data in our AWS serverless api using Nodejs Request package but always get 502 error and can post data from the front end app (React or Jquery).


var dataToPost = {
name: 'ABC',
address: 'XYZ'
}

request(
    { method: 'POST'
    , uri: 'url here...'
    , headers: {
    'User-Agent': 'request'
  } , multipart:
      [ { 'content-type': 'application/json'
        ,  body: JSON.stringify(dataToPost)
        }
      ]
    }
  , function (error, response, body) {
      if(response.statusCode == 201){
        console.log('document saved')
      } else {
        console.log('error: '+ response.statusCode)
        console.log(body)
      }
    }
  )```

Solution

  • If you are able to post data using react and Jquery then probably you are not making a post request correctly.Try this code for post request :

    const request = require('request');
    var dataToPost = {
        name: 'ABC',
        address: 'XYZ'
            }
    const options = {
        url: 'url goes here',
        json: true,
        body: dataToPost
    };
    
    request.post(options, (err, res, body) => {
        if (err) {
            return console.log(err);
        }
        console.log(`Status: ${res.statusCode}`);
        console.log(body);
    });
    

    Alternatively you can also use axios which makes code more readable and have inbuilt promise support:

    const axios = require('axios');
    var dataToPost = {
        name: 'ABC',
        address: 'XYZ'
            }
    const url = 'put url here'
    axios.post(url, data)
        .then((res) => {
            console.log(`Status: ${res.status}`);
            console.log('Body: ', res.data);
        }).catch((err) => {
            console.error(err);
        });
    

    Also check what does AWS Lmbada logs says.