问题描述
我已经研究了一段时间了,但我确实很难被阻止。我想将我的程序从已弃用的请求库迁移到另一个请求库。我选择了 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,stagedDateAfter) => {
let options = {
json: true,body: {
"summary": false,"page": {"max": size}
}
};
axios.post(apiUrl,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 等,但我似乎无法获得正确的格式。
解决方法
解决了!正确的格式让我可以正确访问正文。
let options = {
url: stringURL,method: 'POST',json: true,headers: {
'Accept': 'application/json','Content-Type': 'application/json'
},data: {
"summary": false,"sort": [{"stagedDate": "asc"}],"search_after": [stagedDateAfter],"queries": [],"page": {"max": size}
}
};
axios(options)
.then((response)=>{
//rest of code