ลองใช้ Interceptor Feature หนึ่งใน Axios สำหรับ Call API

O2fullfeel
Sep 5, 2018 · 1 min read

เกริ่น…

หลายๆคนที่ทำงานฝั่ง frontent คงเคยใช้ axios ในการ call api มาบ้างแล้วนะครับ
blog นี้จะมาแนะนำการใช้งาน axios interceptor เป็น feature หนึ่งใน axios ครับลอง install กันก่อยยเลย

npm install axios --save

axios interceptor จะมาช่วยจัดการเมื่อเราต้องการ call api แล้วมีงานที่ต้องทำทุกๆครั้งๆก่อน call api เช่นการเชค token หรือการแนบ token ไปกับ header ทุกๆ request เป็นต้น โดย flow จะออกมาประมาณนี้ครับ

Axios With Interceptor

ตัวอย่างการ call api ด้วย axios แบบ interceptor โดยตัวอย่างจะสร้าง file แยกออกมาสมมุติชื่อ HttpClient.js เพื่อเป็น file หลักในการทำของที่เราจะทำซ้ำๆในตัวอย่างคือเชค token และแนบ header ครับ

ตัวอย่างการเรียกใช้คือ import component HttpClient เข้ามาใน component ที่ต้องการแล้วทำการเรียกใช้ตามตัวอย่าง code ด้านล่าง

เพียงเท่านี้ทุกๆ request ที่เราทำการ call api ก็จะทำการ check token ก่อนที่จะส่งไปกับ header แล้ว

Axios Without Interceptor

ตัวอย่างการ call api ด้วย axios แบบธรรมปกติ

คือถ้าไม่ใช้ interceptor เราก็ต้องมาเขียนแนบ header เองทุกๆ request แบบนี้ก็จะถึกๆหน่อยนะครับขอบคุณทุกท่านที่หลงเข้ามาอ่าน บั๊ยยย

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade