我刚刚成功地 curl 在这里:
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 时,它会返回:失败并出现错误“请求已完成但不正常”
不确定我是否在某个地方做错了什么,但似乎一切都正确地从 CURL 映射到 axios
最佳答案
您有一些问题:
- 在您的
.then(...)
处理程序中,您正在执行控制台日志,但您没有从该函数返回任何内容。因此,res
将是undefined
。 - 您正在
res
上执行JSON.stringify
。res
将是一个 axios 响应,而不是响应正文。将 axios 响应字符串化是一个坏主意,因为它包含大量的对象引用和循环引用。您希望res.data
为您提供响应数据。 - 从axios返回的错误也可能包含这些重对象和循环引用。根据我的经验,当尝试序列化来自 axios 的响应和错误时,实际上可能会导致 Node 崩溃。
以下是我修改您的函数的方法:
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
}
}
};
关于javascript - 如何将CURL请求转换为axios请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58632467/