问题
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