How to use stRequest method in apimocker

Best JavaScript code snippet using apimocker

index copy.ts

Source:index copy.ts Github

copy

Full Screen

1import axios from 'axios'2import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'3import { ElLoading } from 'element-plus'4/**5 * 2.对实例对象中config属性的扩展,增加了一个 STInterceptors 类型6 */7// <T = AxiosResponse> 泛型默认值为 AxiosResponse8interface STInterceptors<T = AxiosResponse> {9 requestInterceptor?: (config: AxiosRequestConfig) => AxiosRequestConfig10 requestInterceptorCatch?: (err: any) => any11 responseInterceptor?: (res: T) => T12 responseInterceptorCatch?: (err: any) => any13}14// 3.扩展原先的config对象可以添加 interceptor,isShow 属性15interface STRequestConfig<T = AxiosResponse> extends AxiosRequestConfig {16 // interceptors参数可以不传17 stInterceptors?: STInterceptors<T>18 isShow?: boolean19}20// 1.封装自己的Axios类21class STAxios {22 instance: AxiosInstance23 stInterceptors?: STInterceptors24 // 控制loading的显示隐藏25 loading?: any26 isShow?: boolean27 constructor(config: STRequestConfig) {28 // 如果需要可实现多个实例对象29 this.instance = axios.create(config)30 this.stInterceptors = config.stInterceptors31 // config.isShow ?? true 空值合并运算符, 如果 config.isShow 为空设置默认值为 true32 this.isShow = config.isShow ?? true33 // 4.1.给当前实例添加所有拦截器34 this.instance.interceptors.request.use(35 // ?.可选链 拦截器存在,执行后面的方法36 this.stInterceptors?.requestInterceptor,37 this.stInterceptors?.requestInterceptorCatch38 )39 this.instance.interceptors.response.use(40 this.stInterceptors?.responseInterceptor,41 this.stInterceptors?.responseInterceptorCatch42 )43 // 4.2.给所有实例添加所有拦截器44 this.instance.interceptors.request.use(45 (config) => {46 // 请求数据过程中显示 loading47 if (this.isShow) {48 this.loading = ElLoading.service({49 lock: true,50 text: 'Loading',51 background: 'rgba(0, 0, 0, 0.7)'52 })53 }54 // console.log('所有实例都有拦截器,并且请求拦截成功~')55 return config56 },57 (err) => {58 // console.log('所有实例都有拦截器,并且请求拦截失败~')59 return err60 }61 )62 this.instance.interceptors.response.use(63 (res) => {64 // 请求成功关闭 loading65 // ?. es11 可选链, 如果前面有值,执行后面操作66 this.loading?.close()67 // console.log('所有实例都有拦截器,并且响应拦截成功~')68 // console.log('直接返回有效信息data: ' + res.data)69 return res.data70 },71 (err) => {72 // if (err.data.status === '404') {73 // console.log('没有当前页面~')74 // }75 // console.log('所有实例都有拦截器,并且响应拦截失败~')76 return err77 }78 )79 }80 request<T>(config: STRequestConfig<T>): Promise<T> {81 // request(config: STRequestConfig) {82 return new Promise((resolve, reject) => {83 // 4.3.1 对单个请求的拦截处理84 if (config.stInterceptors?.requestInterceptor) {85 // 将执行了的requestInterceptor的返回值赋值给config86 config = config.stInterceptors.requestInterceptor(config)87 }88 // 4.3 某个实例的单独请求拦截89 this.instance90 // request<T = any, R = AxiosResponse<T>, D = any> 默认修改的是第二个泛型91 .request<any, T>(config)92 .then((res) => {93 // 4.3.2 对单个响应的拦截处理94 if (config.stInterceptors?.responseInterceptor) {95 res = config.stInterceptors.responseInterceptor(res)96 }97 resolve(res)98 })99 .catch((err) => {100 reject(err)101 })102 })103 }104 // 5. 其他方法封装105 get<T>(config: STRequestConfig<T>): Promise<T> {106 return this.request<T>({ ...config, method: 'get' })107 }108 post<T>(config: any): Promise<T> {109 return this.request<T>({ ...config, method: 'post' })110 }111 delete<T>(config: STRequestConfig<T>): Promise<T> {112 return this.request<T>({ ...config, method: 'delete' })113 }114 patch<T>(config: STRequestConfig<T>): Promise<T> {115 return this.request<T>({ ...config, method: 'patch' })116 }117}...

Full Screen

Full Screen

index.ts

Source:index.ts Github

copy

Full Screen

1import axios from 'axios'2import type { AxiosInstance } from 'axios'3import type { STRequestInterceptors, STRequestConfig } from './type'4import { ElLoading } from 'element-plus'5import { LoadingInstance } from 'element-plus/lib/components/loading/src/loading'6const DEAFULT_LOADING = true7class STRequest {8 instance: AxiosInstance9 interceptors?: STRequestInterceptors10 showLoading: boolean11 loading?: LoadingInstance12 constructor(config: STRequestConfig) {13 // 创建axios实例14 this.instance = axios.create(config)15 // 保存基本信息16 this.showLoading = config.showLoading ?? DEAFULT_LOADING17 this.interceptors = config.interceptors18 // 使用拦截器19 // 1.从config中取出的拦截器是对应的实例的拦截器20 this.instance.interceptors.request.use(21 this.interceptors?.requestInterceptor,22 this.interceptors?.requestInterceptorCatch23 )24 this.instance.interceptors.response.use(25 this.interceptors?.responseInterceptor,26 this.interceptors?.responseInterceptorCatch27 )28 // 2.添加所有的实例都有的拦截器29 this.instance.interceptors.request.use(30 (config) => {31 if (this.showLoading) {32 this.loading = ElLoading.service({33 lock: true,34 text: '正在请求数据....',35 background: 'rgba(0, 0, 0, 0.5)'36 })37 }38 return config39 },40 (err) => {41 return err42 }43 )44 this.instance.interceptors.response.use(45 (res) => {46 // 将loading移除47 this.loading?.close()48 const data = res.data49 if (data.returnCode === '-1001') {50 console.log('请求失败~, 错误信息')51 } else {52 return data53 }54 },55 (err) => {56 // 将loading移除57 this.loading?.close()58 // 例子: 判断不同的HttpErrorCode显示不同的错误信息59 if (err.response.status === 404) {60 console.log('404的错误~')61 }62 return err63 }64 )65 }66 request<T = any>(config: STRequestConfig<T>): Promise<T> {67 return new Promise((resolve, reject) => {68 // 1.单个请求对请求config的处理69 if (config.interceptors?.requestInterceptor) {70 config = config.interceptors.requestInterceptor(config)71 }72 // 2.判断是否需要显示loading73 if (config.showLoading === false) {74 this.showLoading = config.showLoading75 }76 this.instance77 .request<any, T>(config)78 .then((res) => {79 // 1.单个请求对数据的处理80 if (config.interceptors?.responseInterceptor) {81 res = config.interceptors.responseInterceptor(res)82 }83 // 2.将showLoading设置true, 这样不会影响下一个请求84 this.showLoading = DEAFULT_LOADING85 // 3.将结果resolve返回出去86 resolve(res)87 })88 .catch((err) => {89 // 将showLoading设置true, 这样不会影响下一个请求90 this.showLoading = DEAFULT_LOADING91 reject(err)92 return err93 })94 })95 }96 get<T = any>(config: STRequestConfig<T>): Promise<T> {97 return this.request<T>({ ...config, method: 'GET' })98 }99 post<T = any>(config: any): Promise<T> {100 return this.request<T>({ ...config, method: 'POST' })101 }102 delete<T = any>(config: STRequestConfig<T>): Promise<T> {103 return this.request<T>({ ...config, method: 'DELETE' })104 }105 patch<T = any>(config: any): Promise<T> {106 return this.request<T>({ ...config, method: 'PATCH' })107 }108}...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const API_ENDPOINT = 'http://stapi.co/api/v1/rest/';2const stRequest = new XMLHttpRequest();3let query = '';4let userInput = 'search';5let category = '';6//define const variables for DOM elements7const inputSelector = document.querySelector('#input');8const categorySelector = document.querySelector('#category');9const buttonSelector = document.querySelector('#button');10const buttonClearSelector = document.querySelector('#buttonClear');11const errorSelector = document.querySelector('#error');12const answerSelector = document.querySelector('#answer');13function showAnswer(response) {14 if (category === 'movie') category = 'movies';15 if (category === 'astronomicalObject') category = 'astronomicalObjects';16 if (category === 'character') category = 'characters';17 if (category === 'location') category = 'locations';18 if (category === 'movie') category = 'movies';19 if (category === 'season') category = 'seasons';20 if (category === 'spacecraft') category = 'spacecrafts';21 if (category === 'weapon') category = 'weapons';22 let myList = response[category];23 for (let i = 0; i < myList.length; i++) {24 let li = document.createElement('li');25 li.appendChild(26 category === 'movies' || category === 'seasons' || category === 'series'27 ? document.createTextNode(myList[i].title)28 : document.createTextNode(myList[i].name)29 );30 answerSelector.appendChild(li);31 }32 buttonSelector.setAttribute('disabled', 'disabled');33}34function showError(error) {35 errorSelector.innerHTML = error;36 errorSelector.style.visibility = 'visible';37 setTimeout(() => {38 errorSelector.style.visibility = 'hidden';39 }, 3000);40}41//Connect to API and get data42function getData() {43 query = API_ENDPOINT + category + '/' + userInput;44 stRequest.open('GET', query);45 stRequest.responseType = 'json';46 stRequest.onload = function () {47 showAnswer(stRequest.response);48 };49 stRequest.onerror = function () {50 showError('There was an error! Please select category.');51 };52 stRequest.send();53}54function clearData() {55 answerSelector.innerHTML = '';56 buttonSelector.removeAttribute('disabled');57}58//Begin search59category = categorySelector.addEventListener('click', e => (category = e.target.value));60//inputSelector.addEventListener('input', e => (userInput = e.target.value));61buttonSelector.addEventListener('click', getData);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var apimocker = require('apimocker');2var stRequest = apimocker.stRequest;3var stResponse = apimocker.stResponse;4var stMock = apimocker.stMock;5var stScenario = apimocker.stScenario;6var stConfig = apimocker.stConfig;7var stUtils = apimocker.stUtils;8var mock = stMock('test', stRequest('GET', '/test'), stResponse(200, 'OK'), stScenario('test', true), stConfig('test', true));9var utils = stUtils();10var config = stConfig('test', true);11var scenario = stScenario('test', true);12var request = stRequest('GET', '/test');13var response = stResponse(200, 'OK');14var mocker = apimocker();15mocker.addMock(mock);16mocker.addUtils(utils);17mocker.addConfig(config);18mocker.addScenario(scenario);19mocker.addRequest(request);20mocker.addResponse(response);21mocker.start();22mocker.stop();23mocker.set('test', 'test');24mocker.get('test');25mocker.use('test', 'test');26mocker.getMocks();27mocker.getUtils();28mocker.getConfig();29mocker.getScenarios();30mocker.getRequests();31mocker.getResponses();32mocker.getMock('test');33mocker.getUtil('test');34mocker.getConfig('test');35mocker.getScenario('test');36mocker.getRequest('test');37mocker.getResponse('test');38mocker.removeMock('test');39mocker.removeUtil('test');40mocker.removeConfig('test');41mocker.removeScenario('test');42mocker.removeRequest('test');43mocker.removeResponse('test');44mocker.removeMocks();

Full Screen

Using AI Code Generation

copy

Full Screen

1var stRequest = require('apimocker').stRequest;2var stResponse = require('apimocker').stResponse;3var stMock = require('apimocker').stMock;4var stMocker = require('apimocker').stMocker;5var stMockerRegistry = require('apimocker').stMockerRegistry;6var stMockerConfig = require('apimocker').stMockerConfig;7var stMockerConfigBuilder = require('apimocker').stMockerConfigBuilder;8var stMockerConfigFileLoader = require('apimocker').stMockerConfigFileLoader;9var stMockerConfigFileWriter = require('apimocker').stMockerConfigFileWriter;10var stMockerConfigValidator = require('apimocker').stMockerConfigValidator;11var stMockerRequestHandler = require('apimocker').stMockerRequestHandler;12var stMockerResponseHandler = require('apimocker').stMockerResponseHandler;13var stMockerResponseWriter = require('apimocker').stMockerResponseWriter;14var stMockerServer = require('apimocker').stMockerServer;15var stMockerServerFactory = require('apimocker').stMockerServerFactory;16var stMockerServerStartupHandler = require('apimocker').stMockerServerStartupHandler;17var stMockerUtil = require('apimocker').stMockerUtil;18var stMockerValidator = require('apimocker').stMockerValidator;19var stMockerValidatorFactory = require('apimocker').stMockerValidatorFactory;20var stMockerValidatorRegistry = require('apimocker').stMockerValidatorRegistry;21var stMockerValidatorResult = require('apimocker').stMockerValidatorResult;22var stMockerValidatorResultFactory = require('apimocker').stMockerValidatorResultFactory;23var stMockerValidatorResultRegistry = require('apimocker').stMockerValidatorResultRegistry;24var stMockerValidatorResultWriter = require('apimocker').stMockerValidatorResultWriter;25var stMockerValidatorWriter = require('apimocker').stMockerValidatorWriter;26var stMockerWriterFactory = require('apimocker').stMockerWriterFactory;27var stMockerWriterRegistry = require('apimocker').stMockerWriterRegistry;

Full Screen

Using AI Code Generation

copy

Full Screen

1var stRequest = require('apimocker').stRequest;2var http = require('http');3var options = {4};5var req = http.request(options, function(res) {6 console.log('STATUS: ' + res.statusCode);7 console.log('HEADERS: ' + JSON.stringify(res.headers));8 res.setEncoding('utf8');9 res.on('data', function (chunk) {10 console.log('BODY: ' + chunk);11 });12});13req.end();14{15 "request": {16 },17 "response": {18 }19}20[MIT](LICENSE)

Full Screen

Using AI Code Generation

copy

Full Screen

1var stRequest = require('apimocker').stRequest;2var stResponse = require('apimocker').stResponse;3var stMock = require('apimocker').stMock;4var mock = stMock('mock1', stRequest('/test'), stResponse(200, 'Hello World!'));5module.exports = mock;6Default: `process.cwd()`7Default: `process.cwd()`8Default: `{}`

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run apimocker automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful