Skip to content

http请求

axios

正常情况下无法使用axios 因为他不支持sw ,你可以安装插件@vespaiach/axios-fetch-adapter fetch的适配器。但是你的axios版本必须是0.27.x以下

获取token

ts
let token = '';
const cookies = await chrome.cookies.getAll({
  domain: '.giikin.com',
  // name: 'token',
});
token = cookies.find(item => item.name === 'token')?.value ?? '';

请求实例

ts
import axios from 'axios';
import { ElMessage } from 'element-plus';
import fetchAdapter from '@vespaiach/axios-fetch-adapter';
import type { AxiosError } from 'axios';

const baseUrl = `https://gassapi.giikin.cn`;

const service = axios.create({
  baseURL: baseUrl, //
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 60_000,
  headers: {
    'content-type': 'application/json',
  },
  // sw不能使用axios   添加适配器 并且axios 版本0.27
  adapter: fetchAdapter,
});

// 请求拦截器
service.interceptors.request.use(
  async config => {
    let token = '';
    const cookies = await chrome.cookies.getAll({
      domain: '.giikin.com',
      // name: 'token',
    });
    token = cookies.find(item => item.name === 'token')?.value ?? '';
    if (config.url?.includes('upload') || config.url?.includes('uploadfile')) {
      config.headers!['Content-Type'] = 'multipart/form-data';
    }
    if (!config.params) {
      config.params = {};
    }
    config.params = {
      ...config.params,
      _token: token,
    };
    config.headers!.Authorization = `Bearer ${token}`;
    return config;
  },
  error => {
    console.log(error); // for debug
    return Promise.reject(error);
  },
);
// 添加响应拦截器
service.interceptors.response.use(
  response => {
    if (response.config.url?.includes('/adreport')) return response;
    // 对响应数据做点什么
    const res = response.data;
    if (res.code == 401) {
      ElMessage.error('登录失效,请重新登录');
      return response;
    } else if (res.code != 0 && res.code != 401) {
      ElMessage({
        message: res.comment ?? res.message,
        type: 'error',
        duration: 5 * 1000,
      });
    }
    return response;
  },
  (err: AxiosError<any>) => {
    let message: string;
    if (err?.response?.status === 401 && !err.message.includes('timeout')) {
      ElMessage.error('登录失效,请重新登录');
      return;
    } else if (err.response?.data?.message) {
      message = err.response?.data?.message;
    } else {
      message = err.message.includes('timeout') ? '请求超时' : err.message;
    }
    // 对响应错误做点什么
    ElMessage({
      message,
      grouping: true,
      type: 'error',
      duration: 5 * 1000,
    });
    return Promise.reject(err);
  },
);

export default service;

contentScripts中发送请求

你需要先将请求消息发送至background.js中,然后在background.js中发送真实请求。

contentScripts代码

ts
const { data } = await gassChromeRuntimeSendMessage<any, { code: number; data: ThirdPlatformCategoryResponse[] }>({
  type: 'thirdPlatformCategory',
  content: {
    platformName: platformItem.value.platform,
    id: platformItem.value.id,
  },
});

background代码

ts
// 此回调函数不能异步
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
// 获取平台下的分类
  if (request.type === 'thirdPlatformCategory') {
    // 真实接口
    thirdPlatformCategory(request.content)
      .then(data => sendResponse(data))
      .catch(e => sendResponse(e));

    return true;
  }

});

发送消息 & 拦截器

ts
import { ElMessage, MessageProps } from 'element-plus';
import type { MessageParams } from 'element-plus';
import type { AxiosResponse } from 'axios';
import type { AppContext } from 'vue';
import { root } from '@/contentScripts';
/**
 * 发送请求
 * @param message
 * @returns
 */
export const gassChromeRuntimeSendMessage = async <M = any, R = any>(message: M) => {
  const data = await chrome.runtime.sendMessage(message);
  return responseInterceptors<R>(data);
};
/**响应拦截器 */
export const responseInterceptors = <T>(response: any): AxiosResponse<T, any> => {
  console.log(response, 'responseInterceptors');
  if (response?.data) {
    if (response.config.url?.includes('/adreport')) return response;
    // 对响应数据做点什么
    const res = response.data;
    if (res.code == 401) {
      contentScriptsMessage({
        type: 'error',
        message: '登录失效,请重新登录',
      });
      return response;
    } else if (res.code != 0 && res.code != 200 && res.code != 401) {
      contentScriptsMessage({
        message: res.comment ?? res.message,
        type: 'error',
        duration: 5 * 1000,
      });
    }
    return response;
  } else {
    let message: string;
    if (response?.response?.status === 401 && !response.message.includes('timeout')) {
      contentScriptsMessage({
        type: 'error',
        message: '登录失效,请重新登录',
      });
      throw Promise.reject(response);
    } else if (response?.response?.data?.message) {
      message = response.response?.data?.message;
    } else {
      message = response?.message.includes('timeout') ? '请求超时' : response?.message;
    }
    // 对响应错误做点什么
    contentScriptsMessage({
      message,
      grouping: true,
      type: 'error',
      duration: 5 * 1000,
    });
    throw Promise.reject(response);
  }
};
export const contentScriptsMessage = (options: MessageParams, appContext?: null | AppContext) => {
  ElMessage({ appendTo: root as HTMLElement, ...(options as any) }, appContext);
};

Released Under The MIT License.