如何将CURL请求转换为axios请求? [英] How to convert a CURL request into an axios request?
本文介绍了如何将CURL请求转换为axios请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚刚成功地卷曲在这里:
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'
现在我想在lambda中使用axios
now I want to use axios inside my lambda
所以我有这个:
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"
but when I trigger the lambda it returns with: failed with the error "Request completed but is not OK"
不确定我在某处是否做错了什么,但似乎所有内容都已正确地从CURL映射到axios
not sure if I'm doing something wrong somewhere but seems to be everything is correctly mapped from CURL to axios
推荐答案
您遇到了一些问题:
- 在您的
.then(...)
处理程序中,您正在执行控制台日志,但是您并未从该函数中返回任何内容.因此,res
将成为undefined
. - 您正在
res
上执行JSON.stringify
.res
是 axios响应,而不是响应正文.对axios响应进行字符串化是一个坏主意,因为它包含大量对象引用以及循环引用.您希望res.data
为您提供响应数据. - 从Axios返回的错误也可能包含这些重对象和循环引用.以我的经验,当尝试序列化来自axios的响应和错误时,您实际上可能使节点崩溃.
- In your
.then(...)
handler, you are doing a console log, but you aren't returning anything from that function. Therefore,res
is going to beundefined
. - You're doing a
JSON.stringify
onres
.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 wantres.data
to give you the response data. - 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
}
}
};
这篇关于如何将CURL请求转换为axios请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文