如何在组件中使用 next-i18next 更改 axios 标头 Accept-Languags?

问题描述 投票:0回答:1

我尝试导出自定义函数

setLanguageHeader
来更改我的 axios 标头
Accept-Language

我像这样打包 axios 文件:

请求.ts:

import axios, { AxiosRequestConfig } from 'axios';

let baseURL = 'My test API url';
const timeout = 30000;

const serviceWithSessing = axios.create({
    timeout,
    baseURL,
    withCredentials: true,
});

serviceWithSessing.interceptors.request.use(
    (config: any) => {
        let customHeaders: any = {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': true,
            'Accept-Language': 'zh-TW',
        };
        config.headers = customHeaders;
        return config;
    },
    error => {
        console.log('interceptors error', error);
        Promise.reject(error);
    }
);

// Function to set the language header
const setLanguageHeader = (language: 'zh' | 'en-US' | 'jp') => {
  serviceWithSessing.defaults.headers.common['Accept-Language'] = language;
};

serviceWithSessing.interceptors.response.use(
    (response: any) => {
        return response;
    },
    error => {
        return error;
    }
);

// axios return data
interface axiosTypes<T> {
    data: T;
    status: number;
    statusText: string;
}

// custome response Type
interface responseTypes<T> {
    code: number;
    msg: string;
    result: T;
}

const requestHandlerWithSession = <T>(
    method: 'get' | 'post' | 'put' | 'delete',
    url: string,
    params: object = {},
    config: AxiosRequestConfig = {}
): Promise<T> => {
    let response: Promise<axiosTypes<responseTypes<T>>>;
    switch (method) {
        case 'get':
            response = serviceWithSessing.get(url, { params: { ...params }, ...config });
            break;
        case 'post':
            response = serviceWithSessing.post(url, { ...params }, { ...config });
            break;
        case 'put':
            response = serviceWithSessing.put(url, { ...params }, { ...config });
            break;
        case 'delete':
            response = serviceWithSessing.delete(url, { params: { ...params }, ...config });
            break;
    }

    return new Promise<T>((resolve, reject) => {
        response
            .then((res: any) => {
                const data = res.data;
                const status = res.status;
                if (status !== 200 && status !== 201 && status !== 204) {
                    if (status == 401) {
                        console.log('Error handle...');
                    }

                    let e = JSON.stringify(data);
                    console.log(`Request error:${e}`);

                    if (res.response.data) {
                        resolve(res.response.data);
                    } else {
                        reject(data);
                    }
                } else {
                    // return correct data
                    console.log('data', data);
                    resolve(data as any);
                }
            })
            .catch(error => {
                let e = JSON.stringify(error);
                console.log(`Internet error:${e}`);
                reject(error);
            });
    });
};

const requestWithSession = {
    get: <T>(url: string, params?: object, config?: AxiosRequestConfig) =>
        requestHandlerWithSession<T>('get', url, params, config),
    post: <T>(url: string, params?: object, config?: AxiosRequestConfig) =>
        requestHandlerWithSession<T>('post', url, params, config),
    put: <T>(url: string, params?: object, config?: AxiosRequestConfig) =>
        requestHandlerWithSession<T>('put', url, params, config),
    delete: <T>(url: string, params?: object, config?: AxiosRequestConfig) =>
        requestHandlerWithSession<T>('delete', url, params, config),
};

export { request, requestWithSession, setLanguageHeader, serviceWithSessing };

然后我在 _app.tsx

 中触发 
setLanguageHeader

import { i18n } from 'next-i18next';
import { setLanguageHeader } from '@/api/request';

setLanguageHeader(i18n?.language);

这样调用API:

import { request, requestWithSession, serviceWithSessing } from './request';

export const GetMarketDetail = <T>(params: { slug: string }) => {
    console.log('serviceWithSessing =>', serviceWithSessing.defaults);
    return requestWithSession.get<T>(
        `/markets/${params.slug}`,
        {},
        {
            timeout: 15000,
        }
    );
};

如果我将语言更改为

jp
,我可以检查 serviceWithSessing.defaults.headers.common 是

{
  Accept: "application/json, text/plain, */*"
  Accept-Language: "jp"
  Content-Type: undefined
}

但是如果我打开 chrome 调试器来检查网络,我可以看到

Accept-Language
没有改变

我检查我的实例

serviceWithSessing
Accept-Language 已更改,但 chrome 网络 Accept-Language 没有更改。如何解决?

reactjs google-chrome next.js axios
1个回答
0
投票
 let customHeaders: any = {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': true,
            'Accept-Language': 'zh-TW', --> Read from cookies
        };
        config.headers = customHeaders;
        return config;

You need to use cookies/local storage to store the current selected language and set it in the header dynamically. You can also set the fallback value if you dont have any cookies
© www.soinside.com 2019 - 2024. All rights reserved.