Moment For Technology

Tarojs-request -- What bike do you need?

Posted on May 26, 2023, 10:18 a.m. by Ross Brown-Anderson
Category: The front end Tag: The front end taro

tarojs-request

The web request library, based on the Taro. Request Koa-compose package, is designed to provide developers with an easy-to-use, easily extensible WAY to call the API.

Taro Materials Community: taro-ext.jd.com/plugin/view...

Github:github.com/Niubility-C...

Npm:www.npmjs.com/package/tar...

Supported functions

  • Typescriptsupport
  • koaonion-madeuseMiddleware mechanism support
  • timeoutsupport
  • A unifiedError handlingway
  • AbortControllerTermination request

The installation

npm install --save tarojs-request
Copy the code

Quick learning

Performing a GET request

import request from 'tarojs-request';

request('https://xxx.xxx.xxx/xxx', { xxx: 'xxx' })
  .then(console.log)
  .catch(console.log);
Copy the code

Performing a POST request

import request from 'tarojs-request';

request('https://xxx.xxx.xxx/xxx', { xxx: 'xxx' }, 'POST')
  .then(console.log)
  .catch(console.log);
Copy the code

tarojs-request API

  • Request 【 request 】
/ / type
function requestResData.ReqData (
  url: string, data? : ReqData, method? :string, extra? : Taro.request.Option,) :PromiseTaro.request.SuccessCallbackResultResponseResData;

/ / case
import request from 'tarojs-request';

request('https://xxx.xxx.xxx/xxx', { xxx: 'xxx' }, 'POST', {
  header: {
    xx: 'xxx',
  },
})
  .then(console.log)
  .catch(console.log);
Copy the code
  • Extend create request instance
/ / type
function extendReqData (initOptions? : Taro.request.Option
       
        
       ) :Request;

/ / case
import { extend } from 'tarojs-request';

const customRequest = extend({
  timeout: 5000}); customRequest('https://xxx.xxx.xxx/xxx', { xxx: 'xxx' }, 'POST', {
  header: {
    xx: 'xxx',
  },
})
  .then(console.log)
  .catch(console.log);
Copy the code

Request configuration

The following are only the items that are added to the Taro. Request configuration

parameter type The default value mandatory instructions
errorHandler (error: Error) = any - no Error handling
timeoutMessage string - no You can customize the prompt copy for timeout. You need to define timeout first
signal AbortSignal - no AbortSignal terminates the request

Response of the structure

The response of structure with Taro. Request. SuccessCallbackResult consistent.

Error handling

Reference umi

import request, { extend } from 'tarojs-request';

const errorHandler = function (error) {
  const codeMap = {
    '021': 'There was an error'.'022': 'Something has gone terribly wrong.'./ /...
  };
  if (error.response) {
    // The request was sent but the server returned a response with a status code other than 2xx
    console.log(error.response.status);
    console.log(error.response.headers);
    console.log(error.data);
    console.log(error.request);
    console.log(codeMap[error.data.status]);
  } else {
    // Request initialization error or no response returned exception
    console.log(error.message);
  }

  throw error; // If throw. the error will continue to be thrown.

  // If return, the value is returned. 'return; 'return undefined, check whether response has a value when processing the result.
  // return {some: 'data'};
};

// 1. Handle as a unified error
const extendRequest = extend({ errorHandler });

// 2. Separate special processing. If unified processing is configured, but a certain API needs special processing. ErrorHandler is passed in as a parameter on request.
request('/api/v1/xxx', { x: 'xxx' }, 'GET', { errorHandler });

// 3. Use promise.catch to do error handling
request('/api/v1/xxx')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    return errorHandler(error);
  });
Copy the code

The middleware

Align with Koa middleware creation and use, allowing developers to gracefully do pre - and post-request enhancement processing.

request.use((ctx, next))

  • CTX (Object) : context objects, including REQ and RES
  • Next (Function) : Calls the next middleware Function

case

import Taro from '@tarojs/taro';
import request from 'tarojs-request';
import { Middleware } from 'koa-compose';
import { Context } from '.. /type';

/**
 * Check network
 *
 * @param {*} _ctx
 * @param {*} next
 * @return {*}* /
const networkCheckMiddleware: MiddlewareContext = async (_ctx, next) = {
  // Get the network status
  const networkState = await Taro.getNetworkType();
  if (networkState.networkType === 'none') {
    throw new Error('Current network unavailable');
  }
  await next();
};

request.use(networkCheckMiddleware);
Copy the code

Tarojs-request provides a built-in middleware, networkCheckMiddleware

Suspend the request

AbortController aborts the request

import request, { AbortController } from 'tarojs-request';

const controller = new AbortController(); // Create a controller
const { signal } = controller; // Returns an AbortSignal object instance, which can be used with/abort a DOM request.

signal.addEventListener('abort'.() =  {
  console.log('aborted! ');
});

request('/api/response_after_1_sec', {
  signal, // This associates the signal and controller with the fetch request and then allows us to abort the request by calling abortController.abort ()
});

// Cancel the request
setTimeout(() =  {
  controller.abort(); // Abort an unfinished DOM request. This can abort the FETCH request, any consumer and stream that responds to the Body.
}, 100);
Copy the code
Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.