Saturday, January 16, 2021

เปรียบเทียบระหว่าง axios กับ Node-Fetch

const http = require('https');
// using module https
const https = require('https')
const data = JSON.stringify({
msg: 'Hello World!!'
})

const options = {
hostname: 'your-domain.com',
port: 443,
path: '/posts',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}

const req = https.request(options, res => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', d => {
process.stdout.write(d)
})
})

req.on('error', error => {
console.error(error)
})

req.write(data)
req.end()
// using axios
const axios = require('axios')
axios
.post('https://your-domain.com/posts', {
msg: 'Hello World!!'
})
.then(res => {
console.log(`statusCode: ${res.statusCode}`)
console.log(res)
})
.catch(error => {
console.error(error)
})

What axios is?

What Node-Fetch is?

Advantage

1. Axios ทำการแปลงข้อมูลเป็น JSON ให้เราโดยอัตโนมัติ

// node-fetch
fetch
('https://your-domain.com/users/')
.then((res) => {
return res.json()
})
// axios
axios.get('https://your-domain.com/users/')
.then((response) => return response)

2. axios จัดการกับ Error Handling ได้ดี

// node-fetch
fetch("https://your-domain.com/500")
.then(function() {
console.log("ok");
}).catch(function() {
console.log("error");
});
// node-fetch
const handleErrors = (res) => {
if (!res.ok) {
throw Error(res.statusText);
}
return res;
}
fetch("https://your-domain.com/500")
.then(handleErrors)
.then(response => console.log("ok") )
.catch(error => console.log(error) );
// axios
try
{
return await axios.get('https://your-domain.com/500');
} catch (err) {
throw err
}

3. Intercept request and response

// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});

4. axios มีความสามารถในการ Monitor POST request

https://github.com/axios/axios/blob/master/examples/upload/index.html
From: https://github.com/rikmms/progress-bar-4-axios/
Image for post
From: https://github.com/rikmms/progress-bar-4-axios/

5. Cancel Request

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
cancelToken: source.token
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});

axios.post('/user/12345', {
name: 'new name'
}, {
cancelToken: source.token
})

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');

6. axios มีความปลอดภัยมากกว่า และมี Feature Built In Cross Site Forgery (XSRF) Protection

7. มี Browser ที่รองรับ axios เยอะ

Browser support
Browser support: https://github.com/axios/axios

Conclusion

No comments:

Post a Comment