首頁 > web前端 > js教程 > 如何在 Next.js 中實作 Axios 請求攔截器

如何在 Next.js 中實作 Axios 請求攔截器

PHPz
發布: 2024-08-12 20:30:34
原創
943 人瀏覽過

Axios 是一個廣泛使用的 JavaScript 函式庫,可以更輕鬆地向伺服器發送 HTTP 請求。它的突出功能之一是攔截器,它允許我們的應用程式捕獲請求和回應。 Axios 攔截器讓我們可以設定在每個請求或回應到達應用程式之前運行的函數。這對於全域新增身份驗證令牌、日誌記錄和處理錯誤等任務很有幫助,使我們的程式碼更乾淨、更易於管理。

在這篇文章中,我們將學習如何在 Next.js 應用程式中實作 Axios 請求攔截器。我們將從設定 Axios 開始,然後了解如何建立和使用請求和回應攔截器。最後,您將了解如何使用攔截器來改進您的應用程式並保持程式碼井井有條。

設定項目

在深入研究如何在 Next.js 應用程式中實作 Axios 請求攔截器之前,請確保您具備以下條件:

  • 已安裝 Node.js 和 npm/yarn:請確保您的電腦上安裝了 Node.js 和 npm(或紗線)。您可以從這裡下載 Node.js。

  • Next.js 專案設定:您應該要有 Next.js 專案設定。如果您沒有,您可以使用 Create Next App 建立一個新的 Next.js 專案:

npx create-next-app my-axios-app
cd my-axios-app
npm install axios
登入後複製


yarn add axios
登入後複製

實施請求攔截器

Axios 中的請求攔截器可讓您在請求到達伺服器之前對其進行修改。它們對於新增身份驗證令牌、設定自訂標頭或記錄請求非常有用。以下是如何在 Next.js 應用程式中實作 Axios 請求攔截器。

步驟1:建立axios實例

在 lib 資料夾(或專案中的任何首選位置)中建立一個新檔案 axiosInstance.js。您可以將請求攔截器新增到先前建立的 Axios 實例中。該攔截器將在每個請求發出之前執行。

建立 Axios 實例可讓您設定預設配置,例如基本 URL 和標頭,這些配置將套用於使用該實例發出的所有請求。這有助於保持程式碼乾燥(不要重複)。

在 lib 資料夾中建立一個名為 axiosInstance.js 的新檔案並設定您的 Axios 實例:

// lib/axiosInstance.js
import axios from 'axios';

const axiosInstance = axios.create({
  baseURL: 'https://dummyjson.com', // Replace with your API base URL
  timeout: 1000,
  headers: { 'Content-Type': 'application/json' }
});

// Add a request interceptor
axiosInstance.interceptors.request.use(
  function (config) {
    // Do something before the request is sent
    // For example, add an authentication token to the headers
    const token = localStorage.getItem('authToken'); // Retrieve auth token from localStorage
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  function (error) {
    // Handle the error
    return Promise.reject(error);
  }
);

export default axiosInstance;
登入後複製

以下是我們所做工作的總結:

  • 使用 axios.create().
  • 建立了一個 Axios 實例
  • 將 baseURL 設定為 API 的基本 URL。您可以調整它以符合您的 API 的配置。
  • 使用interceptors.request.use()來攔截和修改傳出的請求。這允許我們新增標頭、身份驗證令牌或對請求配置進行其他變更。

步驟 2:在 Next.js 頁面或元件中使用 Axios 實例

設定請求攔截器後,您可以像往常一樣在 Next.js 頁面或元件中使用 Axios 實例。攔截器將在發送每個請求之前自動新增令牌(或執行任何其他配置的操作)。

// pages/index.js
import React, { useEffect, useState } from 'react';
import axiosInstance from '../lib/axiosInstance';

export default function Home() {
  const [data, setData] = useState(null);

  useEffect(() => {
    axiosInstance.get('/products/1') // Replace with your API endpoint
      .then(response => {
        setData(response.data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, []);

  return (
    <div>
      <h1>Data from API</h1>
      {data ? (
        <pre class="brush:php;toolbar:false">{JSON.stringify(data, null, 2)}
) : (

Loading...

)}
); }
登入後複製

How to implement Axios Request Interceptors in Next.js

第三步:自訂攔截器

您可以自訂請求攔截器以根據需要執行其他操作。例如,您可能想要記錄每個請求的詳細資訊:

axiosInstance.interceptors.request.use(
  function (config) {
    // Log the request details
    console.log('Request:', config);
    return config;
  },
  function (error) {
    // Handle the error
    return Promise.reject(error);
  }
);
登入後複製

此設定會將每個請求的詳細資訊記錄到控制台,這有助於偵錯目的。

How to implement Axios Request Interceptors in Next.js

透過在 Next.js 應用程式中實作請求攔截器,您可以確保所有請求在發送之前得到一致的修改或增強,從而提高程式碼的可維護性和功能。

實施響應攔截器

與請求攔截器允許您修改傳出請求的方式類似,Axios 中的回應攔截器可讓您在回應到達應用程式程式碼之前全域管理回應。這對於錯誤處理、回應轉換和日誌記錄等任務特別有用。讓我們探索如何使用 Axios 在 Next.js 應用程式中實作響應攔截器。

第 1 步:建立響應攔截器

在 axiosInstance.js 檔案中,您可以為您建立的 Axios 實例新增回應攔截器。該攔截器將在收到每個回應後執行。

// lib/axiosInstance.js
import axios from 'axios';

const axiosInstance = axios.create({
  baseURL: 'https://dummyjson.com', // Replace with your API base URL
  timeout: 1000,
  headers: { 'Content-Type': 'application/json' }
});

// Add a request interceptor
axiosInstance.interceptors.request.use(
  function (config) {
    // Do something before the request is sent
    const token = localStorage.getItem('authToken'); // Retrieve auth token from localStorage
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  function (error) {
    // Handle the error
    return Promise.reject(error);
  }
);

// Add a response interceptor
axiosInstance.interceptors.response.use(
  function (response) {
    // Do something with the response data
    console.log('Response:', response);
    return response;
  },
  function (error) {
    // Handle the response error
    if (error.response && error.response.status === 401) {
      // Handle unauthorized error
      console.error('Unauthorized, logging out...');
      // Perform any logout actions or redirect to login page
    }
    return Promise.reject(error);
  }
);

export default axiosInstance;
登入後複製

Step 2: Use the Axios Instance in Next.js Pages or Components

With the response interceptor set up, you can use the Axios instance in your Next.js pages or components as usual. The interceptor will automatically handle responses and errors based on your configuration.

// pages/index.js
import { useEffect, useState } from 'react';
import axiosInstance from '../lib/axiosInstance';

export default function Home() {
  const [data, setData] = useState(null);

  useEffect(() => {
    axiosInstance.get('/products/1') // Replace with your API endpoint
      .then(response => {
        setData(response.data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, []);

  return (
    <div>
      <h1>Data from API</h1>
      {data ? (
        <pre class="brush:php;toolbar:false">{JSON.stringify(data, null, 2)}
) : (

Loading...

)}
); }
登入後複製

How to implement Axios Request Interceptors in Next.js

By implementing response interceptors in your Next.js application, you can centralize response handling, improving code maintainability and application robustness. Whether it’s logging, transforming data, or managing errors, response interceptors provide a powerful way to manage HTTP responses efficiently.

Framework-Independent Alternative: Using Requestly

While Axios has powerful tools for processing HTTP requests within applications, integrating and managing interceptors directly within your codebase can be difficult and demand changes to your application’s architecture. Instead of depending on framework-specific solutions such as Axios interceptors, developers can use Requestly, a browser extension that modifies network requests and responses without requiring any changes to the application’s code. This method has various advantages over standard interceptors:

Simplifying Modifications with Requestly

  • No Code Changes Required: Unlike implementing interceptors in your application code, which requires understanding and modifying the codebase, Requestly operates entirely from the browser. This means developers can modify requests and responses dynamically without touching the application’s source code.
  • Flexibility Across Technologies: Requestly’s framework-independent nature allows it to work seamlessly across different projects and technologies. Whether you’re working with React, Angular, Vue.js, or any other framework, Requestly provides a consistent interface for managing network traffic.

Advantages of Using Requestly

  • Ease of Use: Requestly simplifies the process of modifying network requests and responses through an intuitive browser extension interface. This accessibility makes it ideal for developers of all skill levels, from beginners to advanced users.
  • Immediate Testing and Debugging: With Requestly, developers can instantly test and debug different scenarios by altering headers, URLs, or response content. This capability speeds up development cycles and enhances troubleshooting efficiency.
  • Enhanced Privacy and Security: Requestly empowers developers to block or modify requests to enhance privacy, security, and compliance with data protection regulations. For instance, blocking tracking scripts or adding secure headers can be done effortlessly.

Example Use Cases

  • Modify Server Response: Modify response content to simulate various server behaviors without backend changes.
  • Testing Different API Requests: Dynamically alter request to test different API endpoints or data payloads.
  • Blocking Network Request: Test your website under scenarios where certain external resources are unavailable
  • Adding Custom Headers: Add authentication tokens or custom CORS headers for testing APIs that require specific headers. ### How to use Requestly Interceptor

Modify API Response

Requestly allows you to modify API responses. It provides a user-friendly interface for overriding the response body of API requests, allowing you to mimic different data scenarios that your frontend might encounter.

Insert/Inject Script

Insert/Inject Script Rule allows you to inject JavaScript and CSS into web pages as they load. This means you can modify the DOM, change styles, or even add new functionality without altering the source code directly. It’s important for testing hypotheses or debugging during the development and quality assurance process. Learn more about it here.

Replace Rule

Replace Rule enables you to replace a String in URL with another String. This feature is particularly useful for developers to swap the API endpoints from one environment to another or change something specific in the URL. Requests are matched with source condition, and find and replace are performed on those requests by redirecting to the resulting URL. Learn more about this rule here.

結論

在這篇文章中,我們探索了在 Next.js 應用程式中使用 Axios 攔截請求的強大概念。這使得開發人員能夠更好地控制應用程式中的 HTTP 請求和回應。無論是添加身份驗證令牌、記錄用於偵錯目的的請求,還是全域處理錯誤,Axios 攔截器都提供了靈活的解決方案來滿足不同的開發需求。

如果您喜歡這個博客,請查看我們的其他博客,了解如何在 React 中實現 Axios 攔截器

以上是如何在 Next.js 中實作 Axios 請求攔截器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
上一篇:Flutter 狀態管理解釋:如何選擇正確的方法 下一篇:理解乾淨的代碼:有意義的名字 ⚡
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
最新問題
相關專題
更多>
熱門推薦
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板