我有一个应用程序,使用NextJS与getServerSideProps内部的SSR请求(Axios)。
我想知道是否有一种方法来拦截Axios请求和全局添加标题:{ "X-FOO": "BAR" }。
我试过(没有成功):
export function getServerSideProps(context) {
context.req.headers['X-FOO'] = "BAR";
return {
props: {},
};
}如果我直接注入到每个axios请求configHeaders中,它就正确地工作了:
export const getServerSideProps: GetServerSideProps = async(context) => {
const { req } = context;
const configHeaders = {
headers: {
'X-FOO': `BAR`,
}
};
const data = await axios.create({
baseURL: BASE_URL,
}).get(`/path`, configHeaders);
return {
props: {
data,
},
};
}
}
return {
props: {},
};
};我想知道是否有办法在全球范围内为SSR请求添加一个标题。
发布于 2022-10-17 20:12:40
这篇文章有很大的参考价值:https://lazypandatech.com/blog/NextJs/50/REST-API-Call-using-Axios-Interceptor-in-React-NextJs/
在这篇文章的基础上,我将试着一步一步地分解它。
任务:全局集成axios
Api服务:rapi-api
我将使用类型记录和面向对象的概念来演示这个解决方案..。
步骤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();
}
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
调用页面组件中的api服务(BingNewsService)类
export const getServerSideProps: GetServerSideProps = async (ctx) => {
const bingNews = BingNewsService.getInstance();
const res = bingNews.bingNewsData();
return {
props: {
data: res.data,
},
};
};注意到,您可能注意到我们没有一个响应interseptor...is来将事情保持在我们关注的实际问题上。
现在,您可以全局地使用axios头。更好的是,您始终可以扩展抽象类,以配置axios需要使用的任何api服务。
或者,要查看请求数据和更多信息,请执行console.log(res),数据应该在集成终端中,因为请求是在请求时完成的,因此它不会显示在浏览器控制台选项卡上。
我希望这会有所帮助:)
https://stackoverflow.com/questions/73611326
复制相似问题