【问题标题】:How to migrate using request library for a POST request to Axios?如何使用请求库迁移到 Axios 的 POST 请求?
【发布时间】: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


    【解决方案1】:

    解决了!让我正确访问正文的正确格式。

    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
    

    【讨论】:

      猜你喜欢
      • 2017-12-08
      • 1970-01-01
      • 2022-11-02
      • 2020-06-13
      • 2018-06-23
      • 2019-07-23
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多