如何将CURL请求转换为axios请求?

时间:2019-10-30 19:31:24

标签: javascript node.js aws-lambda axios

我刚刚成功地卷曲在这里:

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

现在我想在lambda中使用axios

所以我有这个:

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

但是当我触发lambda时,它会返回:failed with the error "Request completed but is not OK"

不确定我在某处是否做错了什么,但似乎所有内容都已从CURL正确映射到axios

1 个答案:

答案 0 :(得分:1)

您遇到了一些问题:

  1. .then(...)处理程序中,您正在执行控制台日志,但没有返回该功能的任何内容。因此,res将是undefined
  2. 您正在JSON.stringify上进行resres将是 axios响应,而不是响应正文。字符串化axios响应是个坏主意,因为它包含大量对象引用以及循环引用。您希望res.data为您提供响应数据。
  3. 从Axios返回的错误也可能包含这些重对象和循环引用。以我的经验,当尝试序列化来自axios的响应和错误时,实际上会使节点崩溃。

这是我修改您的功能的方法:

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