axios#AxiosRequestConfig TypeScript Examples

The following examples show how to use axios#AxiosRequestConfig. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: fordpass-connection.ts    From homebridge-fordpass with GNU General Public License v3.0 9 votes vote down vote up
async getVehicles(): Promise<Array<any>> {
    if (!this.config.access_token) {
      return [];
    }
    const options: AxiosRequestConfig = {
      method: 'GET',
      url: vehiclesUrl,
      headers: {
        'Content-Type': 'application/json',
        'User-Agent': userAgent,
        'Auth-Token': this.config.access_token,
        'Application-Id': this.applicationId,
      },
    };

    try {
      const result = await axios(options);
      if (result.status === 200 && result.data) {
        return result.data;
      } else {
        this.log.error(`Vehicles failed with status: ${result.status}`);
      }
      return [];
    } catch (error: any) {
      this.log.error(`Vehicles failed with error: ${error.code || error.response.status}`);
      return [];
    }
  }
Example #2
Source File: index.ts    From insta-fetcher with GNU General Public License v3.0 7 votes vote down vote up
/**
	 * Make request to IG API
	 * @param baseURL 
	 * @param url 
	 * @param agent 
	 * @param options 
	 */
	private FetchIGAPI = (baseURL: string, url: string = '', agent: string = config.android, options: AxiosRequestConfig = {}): Promise<AxiosResponse> | undefined => {
		try {
			return axios({
				baseURL,
				url,
				headers: options.headers ? options.headers : this.buildHeaders(agent),
				method: options.method || 'GET',
				...options
			});
		} catch (error: any | AxiosError) {
			if (axios.isAxiosError(error)) {
				throw error.response
			}
		}
	}
Example #3
Source File: rsa_routes.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
// cancel cancels an RSA authentication attempt
    private static cancel(req: Request, res: Response, next: NextFunction) {
        if (req.headers['content-type']?.includes('application/json')) {
            const axiosConfig: AxiosRequestConfig = {
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'client-key': Config.rsa_client_key,
                },
            };

            const payload = plainToClass(RSAStatusRequest, req.body as object);

            axios
                .post(`${Config.rsa_url}/mfa/v1_1/authn/cancel`, payload, axiosConfig)
                .then((response: AxiosResponse) => {
                    const responsePayload = plainToClass(RSAResponse, response.data as object);
                    Result.Success(responsePayload).asResponse(res);
                })
                .catch((e) => {
                    Result.Error(e).asResponse(res);
                })
                .finally(() => next());
        } else {
            res.status(404).json('Unsupported content type');
            next();
        }
    }
Example #4
Source File: requestInterceptor.ts    From react-amis-admin with Apache License 2.0 6 votes vote down vote up
/**
 * 全局请求拦截,方便对错误进行统一处理
 * @param config
 */
export function request(config: AxiosRequestConfig) {
    let instance = axios.create();
    return new Promise((resolve, reject) => {
        let onSuccess = (res:any) => {
            console.log("onSuccess", res);
            if (res.data == null) {
                console.log("reject data")
                reject(res);
            } else if (res.data.status == 40001) {
                // 未登陆
                console.log("redirect url", res.data.redirectUrl)
                window.location.href = res.data.redirectUrl;
            } else if (res.data.status == 40002) {
                // 无权限
                console.log("not permission, url", config.url);
                toast['error']('您无访问权限,请申请!', '消息');
                reject(res);
            } else {
                resolve(res)
            }
        }

        let onFail = (error:any) => {
            console.log("onFail", error)
            reject(error);
        }
        return instance.request(config)
            .then(onSuccess, onFail)
            .catch(onFail);
    })
}
Example #5
Source File: axios.ts    From vue3-ts-base with MIT License 6 votes vote down vote up
/**
 * @description 请求发起前的拦截器
 * @returns {AxiosRequestConfig} config
 */
service.interceptors.request.use(async (config: AxiosRequestConfig) => {
  // 如果是获取token接口:
  if (config.url === '/auth/oauth/token') {
    let userAccount = ''
    // 若存在username,则为登录情况,判断user-account
    if (config.params.username) {
      userAccount = config.params.username.includes('-')
        ? 'ACCOUNT_USER'
        : 'ADMIN_USER'
    } else {
      // 刷新token情况,通过用户信息email是否有值判断
      userAccount = Store.state.user.userDetail.email
        ? 'ADMIN_USER'
        : 'ACCOUNT_USER'
    }

    config.headers['User-Account'] = userAccount
    config.headers.Authorization = 'Basic ZmViczoxMjM0NTY='
  } else {
    // 如果保存有token,则取,否则不添加Authorization
    if (localStorage.vuex && JSON.parse(localStorage.vuex).user?.token) {
      const token = Store.state.user?.token
      const tokenType = token.token_type
      const accessToken = token.access_token
      config.headers.Authorization = `${tokenType} ${accessToken}`
    }
  }

  return config
})
Example #6
Source File: InterceptorManager.ts    From js-sdk with MIT License 6 votes vote down vote up
export class ResponseInterceptor implements InterceptorManager<AxiosRequestConfig> {
  use(resolved: ResolvedFn<AxiosResponse>, rejected?: RejectedFn): number {
    return Axios.interceptors.response.use(resolved, rejected)
  }

  eject(id: number): void {
    Axios.interceptors.response.eject(id)
  }
}
Example #7
Source File: fetcher.ts    From yasd with MIT License 6 votes vote down vote up
fetcher = <T>(requestConfig: AxiosRequestConfig): Promise<T> => {
  return client
    .request<T>(requestConfig)
    .then((res) => res.data)
    .catch((error) => {
      if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        console.error(error.response.data)
        console.error(error.response.status)
        toast.error('请求错误: ' + error.message + `(${error.response.status})`)
      } else if (error.request) {
        // The request was made but no response was received
        // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
        // http.ClientRequest in node.js
        console.error(error.request)
        toast.error('无法连接服务器: ' + error.message, {
          toastId: error.message,
        })
      } else {
        // Something happened in setting up the request that triggered an Error
        console.error('Error', error.message)
        toast.error('发生错误: ' + error.message)
      }

      throw error
    })
}
Example #8
Source File: EpicgamesGraphQLError.ts    From fnbr.js with MIT License 6 votes vote down vote up
/**
   * @param error The raw Epicgames GraphQL API error data
   * @param request The client's request
   */
  constructor(error: EpicgamesGraphQLErrorData, request: AxiosRequestConfig) {
    super();
    this.name = 'EpicgamesGraphQLError';
    this.message = error.message;

    this.url = request.url || '';
    this.serviceResponse = error.serviceResponse && JSON.parse(error.serviceResponse);
    this.locations = error.locations;
    this.path = error.path;
    this.requestData = request.data;
  }
Example #9
Source File: ContentDeliveryAPI.ts    From foundation-lib-spa-core with Apache License 2.0 6 votes vote down vote up
/**
   * Build the request parameters needed to perform the call to the Content Delivery API
   *
   * @param verb The verb for the generated configuration
   */
  protected getRequestSettings(verb?: Method): AxiosRequestConfig {

    let options: AxiosRequestConfig = {
      method: verb ? verb : 'get',
      baseURL: this.config.epiBaseUrl,
      withCredentials: true,
      headers: { ...this.getHeaders() },
      transformRequest: [
        (data: any, headers: any) => {
          if (data) {
            headers['Content-Type'] = 'application/json';
            return JSON.stringify(data);
          }
          return data;
        },
      ],
      responseType: 'json',
    };
    if (this.config.networkAdapter) {
      options.adapter = this.config.networkAdapter;
    }
    return options;
  }
Example #10
Source File: HTTPService.ts    From bada-frame with GNU General Public License v3.0 6 votes vote down vote up
/**
     * Generic HTTP request.
     * This is done so that developer can use any functionality
     * provided by axios. Here, only the set headers are spread
     * over what was sent in config.
     */
    public async request(config: AxiosRequestConfig, customConfig?: any) {
        // eslint-disable-next-line no-param-reassign
        config.headers = {
            ...this.headers,
            ...config.headers,
        };
        if (customConfig?.cancel) {
            config.cancelToken = new axios.CancelToken(
                (c) => (customConfig.cancel.exec = c)
            );
        }
        return await axios({ ...config, ...customConfig });
    }
Example #11
Source File: axiosRequest.ts    From v3-client with Apache License 2.0 6 votes vote down vote up
export async function axiosRequest(options: AxiosRequestConfig): Promise<unknown> {
  try {
    const response = await axios(options);
    return response.data;
  } catch (error) {
    if (error.isAxiosError) {
      if (error.response) {
        throw new AxiosServerError(error.response, error);
      }
      throw new AxiosError(`Axios: ${error.message}`, error);
    }
    throw error;
  }
}
Example #12
Source File: lambda-helpers.ts    From roamjs-com with MIT License 6 votes vote down vote up
getClerkOpts = (
  email: string,
  headers?: Record<string, string>
): AxiosRequestConfig => ({
  headers: {
    Authorization: `Basic ${Buffer.from(email).toString("base64")}`,
    ...headers,
  },
})
Example #13
Source File: ApiBaseService.ts    From devopness-sdk-js with MIT License 6 votes vote down vote up
private defaultAxiosSettings: AxiosRequestConfig = {
        timeout: 30000,
        responseType: 'json',
        headers: {
            common: {
                Accept: "application/json",
                'Content-Type': "application/json",
            },
        },
        withCredentials: false
    }
Example #14
Source File: base.model.ts    From covidnet_ui with GNU Affero General Public License v3.0 6 votes vote down vote up
// Fetch file Arraybuffer from server
  static getFileBufferArrayArray(url: string) {
    const auth = { token: `${window.sessionStorage.getItem("AUTH_TOKEN")}` };
    const header = {
      "Content-Type": "application/vnd.collection+json",
      "Authorization": "Token " + auth.token
    };
    const config: AxiosRequestConfig = {
      headers: header,
      method: "get",
      responseType: "arraybuffer",
      url
    };
    return axios(config);
  }
Example #15
Source File: index.ts    From subsocial-js with GNU General Public License v3.0 6 votes vote down vote up
// ---------------------------------------------------------------------
  // IPFS Request wrapper

  /** Makes a request to the IPFS node */
  private async ipfsNodeRequest (endpoint: IpfsNodeEndpoint, cid?: CID): Promise<AxiosResponse<any>> {
    const config: AxiosRequestConfig = {
      method: 'GET',
      url: `${this.ipfsNodeUrl}/${endpoint}`
    };

    if (typeof cid !== undefined) {
      config.url += `?arg=${cid}`
    }

    return axios(config)
  }
Example #16
Source File: interceptor.ts    From raspiblitz-web with MIT License 6 votes vote down vote up
instance.interceptors.request.use((config: AxiosRequestConfig) => {
  const token = localStorage.getItem("access_token");
  if (token) {
    if (!config.headers) {
      config.headers = {};
    }
    config.headers["Authorization"] = `Bearer ${token}`;
  }
  return config;
});
Example #17
Source File: AxiosClient.ts    From big-o with MIT License 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/no-explicit-any
    post(uri: string, body: string): Promise<any> {
        const config: AxiosRequestConfig = {
            responseType: 'json'
        };
        return axios.post(uri, body, config)
            .then((res: AxiosResponse) => {
                return res.data;
            });
    }
Example #18
Source File: http-proxy-creator.ts    From malagu with MIT License 6 votes vote down vote up
protected createTask(endpoint: string) {
        return async () => {
            const meta = this.requestMap.get(endpoint);
            if (!meta) {
                return;
            }
            clearTimeout(meta.id as any);
            const contents = meta.contents;
            this.requestMap.delete(endpoint);
            const config: AxiosRequestConfig = {
                url: endpoint,
                method: HttpMethod.POST,
                data: contents.length > 1 ? JSON.stringify(contents) : contents[0],
                headers: {
                    [HttpHeaders.CONTENT_TYPE]: MediaType.APPLICATION_JSON_UTF8,
                    [HttpHeaders.X_REQUESTED_WITH]: XML_HTTP_REQUEST
                },
                ...this.options.clientConfig
            };
            await this.options.clientConfigProcessor?.process(config);
            const { data } = await this.options.restOperations.request(config);
            if (Array.isArray(data)) {
                for (const message of data) {
                    const parsed = JSON.parse(message);
                    this.channelMap.get(parsed.id)!.handleMessage(parsed);
                }
            } else {
                this.channelMap.get(data.id)!.handleMessage(data);
            }
        };
    }
Example #19
Source File: testlib.ts    From avalanchejs with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected _TestMethod = async (
    method: string,
    path: string = "",
    getdata: object = {},
    postdata: object = undefined,
    axiosConfig: AxiosRequestConfig = undefined
  ): Promise<object> => {
    if (postdata === undefined) {
      const res: RequestResponseData = await this.core[method](
        this.baseURL + path,
        getdata,
        {},
        axiosConfig
      )
      return this._respFn(res)
    }
    const res: RequestResponseData = await this.core[method](
      this.baseURL + path,
      getdata,
      postdata,
      {},
      axiosConfig
    )
    res.data = JSON.stringify(res.data) // coverage completeness
    return this._respFn(res)
  }
Example #20
Source File: axios.config.ts    From easy-email with MIT License 6 votes vote down vote up
request = {
  async get<T>(url: string, config?: AxiosRequestConfig | undefined) {
    return axiosInstance.get<T>(url, config).then((data) => data.data);
  },
  async post<T>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig | undefined
  ) {
    return axiosInstance.post<T>(url, data, config).then((data) => data.data);
  },
}
Example #21
Source File: siteServices.ts    From aqualink-app with MIT License 6 votes vote down vote up
getSiteSurveyPoints = (
  id: string,
  cancelToken?: AxiosRequestConfig["cancelToken"]
) =>
  requests.send<SurveyPoints[]>({
    url: `site-survey-points?siteId=${id}`,
    method: "GET",
    cancelToken,
  })
Example #22
Source File: http.ts    From airnode with MIT License 6 votes vote down vote up
export function execute(config: AxiosRequestConfig) {
  return axios({
    url: config.url,
    method: config.method,
    headers: config.headers,
    data: config.data,
    params: config.params,
    timeout: config.timeout,
  });
}
Example #23
Source File: BaseServiceClient.ts    From BlinkWebUI with GNU General Public License v3.0 6 votes vote down vote up
private baseRequest(
        config: AxiosRequestConfig
    ): Promise<BaseServiceResponse> {
        const axiosInstance = axios.create();

        this.responseInterceptors.forEach((responseInterceptor) => {
            axiosInstance.interceptors.response.use(
                responseInterceptor.responseInterceptor,
                responseInterceptor.errorResponseInterceptor
            );
        });

        SimplePubSub.publish(PubSubEvent.HTTP_REQUEST_STARTED, axiosInstance);

        return axiosInstance({
            ...config,
            headers: {
                ...(config.headers ?? {}),
                'Cache-Control': 'no-cache',
                Pragma: 'no-cache'
            },
            baseURL: this.baseUrl
        })
            .then((response: AxiosResponse) => {
                SimplePubSub.publish(PubSubEvent.HTTP_REQUEST_SUCCESS, response);
                SimplePubSub.publish(PubSubEvent.HTTP_REQUEST_ENDED, response);
                return response;
            })
            .catch((reason: AxiosError) => {
                SimplePubSub.publish(PubSubEvent.HTTP_REQUEST_FAILED, reason);
                SimplePubSub.publish(PubSubEvent.HTTP_REQUEST_ENDED, reason);
                if (reason.response && [401, 403].includes(reason.response.status)) {
                    SimplePubSub.publish(PubSubEvent.HTTP_REQUEST_UNAUTHORIZED, reason);
                }
                throw reason;
            });
    }
Example #24
Source File: requestInterceptors.ts    From react-starter-boilerplate with MIT License 6 votes vote down vote up
requestSuccessInterceptor = (config: AxiosRequestConfig): AxiosRequestConfig => {
  if (authStorage.accessToken) {
    return {
      ...config,
      headers: {
        ...config.headers,
        Authorization: `Bearer ${authStorage.accessToken}`,
      },
      withCredentials: true,
    };
  }
  return config;
}
Example #25
Source File: index.ts    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
uploadImage = async <T extends File>(file: T): Promise<string> => {
  const formData = createFormData(file);
  const config: AxiosRequestConfig = {
    method: 'post',
    url: IMGUR_UPLOAD_URL,
    headers: {
      Authorization: `Client-ID ${IMGUR_API_CLIENT_ID}`,
    },
    data: formData,
  };

  return axios(config)
    .then((response) => {
      return response.data.data.link;
    })
    .catch((error) => {
      let localizedString = f('map-ui:image-upload-error-generic', {
        code: error.response.status.error.code ?? '???',
      });

      switch (error.response.status) {
        case 400:
          if (error.response.status.error.code === 1003)
            localizedString = t('map-ui:image-upload-error-file-invalid-type');
          break;
        default:
          console.error(error.response);
          break;
      }

      const newError = {
        ...error,
        localizedString,
      };
      throw newError;
    });
}
Example #26
Source File: Request.ts    From valorant.js with MIT License 6 votes vote down vote up
export class Request implements AxiosRequestConfig {
    url: string
    method: Method
    headers: any
    data?: any
    jar?: any
    withCredentials = true
    constructor(url: string, method: Method, headers: any, body?: any, jar?: any) {
        this.url = url;
        this.method = method;
        this.headers = headers;
        this.data = body;
        this.jar = jar;
    }
}
Example #27
Source File: st-client.ts    From smartthings-core-sdk with Apache License 2.0 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/no-explicit-any
	public async redeemCode(authCode: string): Promise<any> {
		const headers = {
			'Content-Type': 'application/x-www-form-urlencoded',
			'Authorization': `Basic ${Buffer.from(this.clientId + ':' + this.clientSecret).toString('base64')}`,
			'Accept': 'application/json',
		}

		const axiosConfig: AxiosRequestConfig = {
			url: this.authURL,
			method: 'POST',
			headers,
			data: `grant_type=authorization_code&code=${authCode}&client_id=${this.clientId}&redirect_uri=${this.redirectUri}`,
		}

		const response = await axios.request(axiosConfig)
		if (response.status > 199 && response.status < 300) {
			return response.data
		}
		throw Error(`error ${response.status} with message ${response.data}`)
	}
Example #28
Source File: Session.ts    From huawei-lte-api-ts with GNU Lesser General Public License v3.0 6 votes vote down vote up
constructor(axios_config: AxiosRequestConfig) {
        const cookieStore = new tough.MemoryCookieStore();
        this.cookieJar = new tough.CookieJar(cookieStore);
        this.axiosInstance = wrapper(axios.create({
            ...axios_config,
            jar: this.cookieJar,
            withCredentials: true
        }));
    }
Example #29
Source File: tdapiinterface.ts    From tda-api-client with GNU General Public License v3.0 6 votes vote down vote up
async function doAuthRequest(authConfig: IAuthConfig, data: any, config?: TacBaseConfig): Promise<IAuthConfig> {
    const requestConfig: AxiosRequestConfig = {
        method: "post",
        url: "/v1/oauth2/token",
        data,
        headers: {
            "Accept": "*/*",
            "Accept-Encoding": "gzip",
            "Accept-Language": "en-US",
            "Content-Type": "application/x-www-form-urlencoded",
            "DNT": 1,
            "Host": "api.tdameritrade.com",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-site",
        },
    };
    const result = await performAxiosRequest(requestConfig, true);

    Object.assign(localAuthData, authConfig);
    Object.assign(localAuthData, result);
    localAuthData.expires_on = Date.now() + (result.expires_in ? result.expires_in * 1000 : 0);
    await writeOutAuthResultToFile(localAuthData, config);
    Object.assign(authConfig, localAuthData);

    return authConfig;
}