How can I improve the elegancy of my code that uses axios?

拈花ヽ惹草 提交于 2020-04-17 18:31:43

问题


I am trying to migrate from request to axios, since request has been deprecated.
Suppose that the url 'https://www.example.com' receives a post request with formdata that contains login information, and also suppose that I need to maintain the current session across multiple requests(for that I need a cookieJar). Using axios I need cookieJar support from an external library therefor I use axios-cookiejar.
Also to send formdata using axios I have to use the external library form-data, and I also have to set the headers manually since axios doesn't do that for me.
I have the following code, which uses axios that does just that:

axios = require('axios')
FormData = require('form-data')
axiosCookieJarSupport = require('axios-cookiejar-support').default
tough = require('tough-cookie')
axiosCookieJarSupport(axios)
cookieJar = new tough.CookieJar()
form = new FormData()
form.append('email', 'example@gmail.com')
form.append('password', '1234')
axios({
    method: 'post',
    url: 'https://www.example.com',
    data: form,
    headers: {'Content-Type': `multipart/form-data; boundary=${form._boundary}` },
    jar: cookieJar,
    withCredentials: true
}).then(function (response) {
    console.log(response['data'])
})

Using request this becomes much simpler:

request = require('request')
requestCookieJar = request.jar()
request.post({
    url: 'https://www.example.com',
    method: 'POST',
    jar: requestCookieJar,
    formData: {
        'email': 'example@gmail.com',
        'password': '1234'
    }
}, function(error, response, body) {
    console.log(body)
})

As you can see the request API is much more elegant.
Is there a way to use axios more elegantly or is there a different elegant API, which isn't deprecated, that I could use to support my needs stated at the beginning of this question?

来源:https://stackoverflow.com/questions/60894678/how-can-i-improve-the-elegancy-of-my-code-that-uses-axios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!