How to convert a CURL request into an axios request?

隐身守侯 提交于 2019-12-13 07:17:26

问题


I just successfully curled here:

curl -X POST https://jenkins-url/job/MyJob/job/some-job/job/master/build --user myemail:mypassword -H 'Jenkins-Crumb: mycrumb'

now I want to use axios inside my lambda

so I have this:

const axios = require('axios')
exports.handler = async (event) => {
      const url = "my-url";
      try {
        const res = await axios.post(url, {}, {
            auth: {
              username: 'user',
              password: 'passowrd'
            },
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "Jenkins-Crumb": "my-crumb"
            },
          }).then(function(response) {
            console.log('Authenticated');
          }).catch(function(error) {
            console.log('Error on Authentication');
          });
        console.log(res)
        return {
            statusCode: 200,
            body: JSON.stringify(res)
        }
    } catch (e) {
        console.log(e)
        return {
            statusCode: 400,
            body: JSON.stringify(e)
        }
    }
};

but when I trigger the lambda it returns with: failed with the error "Request completed but is not OK"

not sure if I'm doing something wrong somewhere but seems to be everything is correctly mapped from CURL to axios


回答1:


You have a few issues:

  1. In your .then(...) handler, you are doing a console log, but you aren't returning anything from that function. Therefore, res is going to be undefined.
  2. You're doing a JSON.stringify on res. res would be an axios response, not the response body. Stringifying the axios response is a bad idea, because it contains hefty object references and also circular references. You want res.data to give you the response data.
  3. The error returned from Axios may also contain these heavy objects and circular references. In my experience, you can actually crash node when trying to serialize responses and errors from axios.

Here's how I'd modify your function:

const axios = require('axios')

exports.handler = async (event) => {
  const url = "my-url";
  try {
    const res = await axios.post(url, {}, {
      auth: {
        username: 'user',
        password: 'passowrd'
      },
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Jenkins-Crumb": "my-crumb"
      },
    });

    return {
      statusCode: 200,
      body: JSON.stringify(res.data)
    }
  } catch (e) {
    console.log(e)
    return {
      statusCode: 400,
      // Don't do JSON.stringify(e). 
      // e.response.data will be the axios response body,
      // but e.response may be undefined if the error isn't an HTTP error
      body: e.stack
    }
  }
};


来源:https://stackoverflow.com/questions/58632467/how-to-convert-a-curl-request-into-an-axios-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!