我刚刚成功地卷曲在这里:
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
答案 0 :(得分:1)
您遇到了一些问题:
.then(...)
处理程序中,您正在执行控制台日志,但没有返回该功能的任何内容。因此,res
将是undefined
。JSON.stringify
上进行res
。 res
将是 axios响应,而不是响应正文。字符串化axios响应是个坏主意,因为它包含大量对象引用以及循环引用。您希望res.data
为您提供响应数据。这是我修改您的功能的方法:
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
}
}
};