【问题标题】:NextJS SSR - Axios Global Header (getServerSideProps)NextJS SSR - Axios 全局标头 (getServerSideProps)
【发布时间】:2022-10-18 04:12:40
【问题描述】:

我有一个在 getServerSideProps 中使用 NextJS 和 SSR 请求(Axios)的应用程序。

想知道有没有办法拦截Axios SSR请求并全局添加header:{ "X-FOO": "BAR" }

我试过(不成功):

export function getServerSideProps(context) {
  context.req.headers['X-FOO'] = "BAR";

  return {
    props: {},
  };
}

如果我直接注入每个 axios 请求配置标头它工作正常:

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 请求全局添加标头。

【问题讨论】:

标签: reactjs next.js axios server-side-rendering


【解决方案1】:

这篇文章很有帮助 参考: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) 数据应该在您的集成终端中,因为请求是在 请求,因此它不会显示在浏览器控制台选项卡上。

我希望这有帮助:)

【讨论】:

    猜你喜欢
    • 2021-09-25
    • 2023-02-18
    • 2017-05-01
    • 2019-04-11
    • 2021-08-27
    • 2023-03-14
    • 2020-09-12
    • 2020-12-19
    • 2021-07-15
    相关资源
    最近更新 更多