【发布时间】:2021-05-17 23:11:28
【问题描述】:
我已经对此进行了一段时间的研究,但绝对难以阻止。我想将我的程序从已弃用的请求库迁移到另一个库。我选择了 axios 但无法让它工作。我需要做的就是以类似的方式发出发布请求,让我可以访问响应正文。
这是我的不推荐使用的库请求代码:
const getPage = (apiUrl, size, stagedDateAfter) => {
let options = {
json: true,
body: {
"summary": false,
"sort": [{"stagedDate": "asc"}],
"search_after": [stagedDateAfter],
"queries": [],
"page": {"max": size}
}
};
request.post(apiUrl, options, (error, res, body) => {
if (error) {
return console.log(error)
}
if (!error && res.statusCode === 200 && keepGoing == true) {
if(body.meta.total == 0 || (!body)){
throw("error");
}
/*
Code works from this point, can access body, data, etc
*/
}
}
我的失败的 axios 库代码:
function checkResponseStatus(res) {
if(res.statusCode === 200 && keepGoing == true) {
return res
} else {
throw new Error(`The HTTP status of the reponse: ${res.status} (${res.statusText})`);
}
}
const headers = {
'Content-Type': 'application/json'
}
const getPage = (apiUrl, size, stagedDateAfter) => {
let options = {
json: true,
body: {
"summary": false,
"sort": [{"stagedDate": "asc"}],
"search_after": [stagedDateAfter],
"queries": [],
"page": {"max": size}
}
};
axios.post(apiUrl, options, headers)
.then(response => {
console.log(response);
if(!response){
checkResponseStatus(response);
}
return response;
})
.catch(error => {
console.log(error.res)
})
.then(data => { //This code doesn't work since response not defined here
if(response.data.status == 200){
console.log(data);
}
});
我所需要的只是能够使用 axios 访问响应正文,类似于我使用请求库的方式,但我正在阅读文档、api 等,但我似乎无法获取正确的格式。
【问题讨论】:
标签: api post request axios migrate