这篇文章很有帮助
参考:https://lazypandatech.com/blog/NextJs/50/REST-API-Call-using-Axios-Interceptor-in-React-NextJs/
基于这篇文章,我将尝试逐步分解它
任务: 全局集成 axiosAPI服务: 拉皮API
我将使用 typescript 和 OOP 概念来演示这个解决方案......
步骤1:
创建一个抽象类,我们将这个类称为“AxiosBaseService”
import axios, { AxiosInstance, AxiosRequestConfig } from "axios";
export abstract class AxiosBaseService {
protected instance: AxiosInstance;
protected token?: string;
protected readonly baseURL: string;
public constructor(baseURL: string, token?: string) {
this.baseURL = baseURL;
this.instance = axios.create({
baseURL,
});
this.token = token;
this.initializeRequestInterceptor();
// this.initializeResponseInterceptor();
}
private initializeRequestInterceptor = () => {
this.instance.interceptors.request.use(this.handleRequest);
};
private handleRequest = (config: AxiosRequestConfig) => {
// config.headers!["Authorization"] = `Bearer ${this.token}`;
config.headers!["Accept-Language"] = "EN";
config.headers!["X-BingApis-SDK"] = "true";
config.headers!["X-RapidAPI-Key"] = "secret_key";
config.headers!["X-RapidAPI-Host"] = "bing-news-search1.p.rapidapi.com";
return config;
};
}
第2步:
创建 api 服务类,然后该类将扩展抽象类,在继承所有方法和字段(如果有)的过程中。
在我们的例子中,我们只需要构造函数。
import { AxiosBaseService } from "./AxiosBaseService";
export class BingNewsService extends AxiosBaseService {
private static classInstance?: BingNewsService;
constructor() {
super("https://bing-news-search1.p.rapidapi.com");
}
public static getInstance() {
if (!this.classInstance) {
this.classInstance = new BingNewsService();
}
return this.classInstance;
}
public bingNewsData = () => {
this.instance
.get("/news", {
params: { cc: "us", safeSearch: "on", textFormat: "Raw" },
})
.then((response) => {
if (response) {
console.log(response.data);
return response;
}
});
};
}
第 3 步
在页面组件(SSR)中调用 api 服务(BingNewsService)类
export const getServerSideProps: GetServerSideProps = async (ctx) => {
const bingNews = BingNewsService.getInstance();
const res = bingNews.bingNewsData();
return {
props: {
data: res.data,
},
};
};
现在您可以全局使用 axios 标头。
更好的是,您始终可以扩展抽象类来配置您需要与 axios 一起使用的任何 api 服务。
或者查看您的请求数据和更多信息,请执行 console.log(res)
数据应该在您的集成终端中,因为请求是在
请求,因此它不会显示在浏览器控制台选项卡上。
我希望这有帮助:)