New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@ourea/fetch

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@ourea/fetch

easy to use fetch lib

  • 1.2.4
  • npm
  • Socket score

Version published
Weekly downloads
4
increased by300%
Maintainers
1
Weekly downloads
 
Created
Source

@ourea/fetch

安装

$ npm install @ourea/fetch --save

使用

import Http, { HttpError } from '@ourea/fetch'

const http = Http(opt)

初始化配置

const httpConfig = {
  conf: {
    credentials: 'include',
    baseUrl: '/api',
    headers: {
      Accept: 'application/json',
      // 'Content-Type': 'application/json',
    },
    timeout: 5000,
  },
  before: [
    ([url, opt]) => {
      console.log('hook1', url, opt)
    },
    ([url, opt]) => {
      console.log('hook2', url, opt)
    },
  ],
  after: [
    (rsp) => {
      console.log('after hook1', rsp)
    },
  ],
}
配置说明默认值其它
allowclient 允许的请求类型['get', 'post', 'put', 'delete', 'upload', 'download']可选
before前置钩子(钩子数组)[]可选
after后置钩子(钩子数组)[]可选
conffetch配置项参考fetch api 文档
error全局错误处理函数null可选

方法

  • get(url, [parmas], [options]) // 基于初始化配置的 allow
  • post(url, [parmas], [options]) // 基于初始化配置的 allow
  • put(url, [parmas], [options]) // 基于初始化配置的 allow
  • delete(url, [parmas], [options]) // 基于初始化配置的 allow
  • upload(url, [parmas], [options]) // 基于初始化配置的 allow
  • download(url, [parmas], [options]) // 基于初始化配置的 allow
  • setErrorHook(func) 设置全局错误处理器
  • injectBefore(func) 增加前置拦截器
  • injectAfter(func) 增加后置拦截器

内置error code

  • HTTP_STATUS_ERROR - 服务器未正常响应
  • REQUEST_TIMEOUT - 请求超时
  • TOKEN_EXPIRE - token校验失败
  • RESPONSE_PARSING_FAILED - reponse 解析出错

injectAfter function

如果injectAfter function有返回值且返回值是HttpError的实例的话,当前请求的promise会被reject, 这次请求的失败信息将也会触发onError事件。

例子

http.injectAfter(function(rsp){
  // do some response check

  return new vFetch.HttpError({
    code: '001',
    message: 'error test',
    httpStatus: null,
  })
})

Content-Type

为了方便使用,下面这几种情况下vFetch会根据content-type去自动设置request body的类型, 处理body对象的构建

  • application/x-www-form-urlencoded (默认) 如果传入的params是object类型,则自动构建请求body
  • multipart/form-data 自动根据请求的parmas object 构建 FromData对象
  • application/json 如果传入的params是object类型,则自动转换成JsonString,如果为string类型,则直接用传入的params

请求的params为FormData类型时,request的body不会进行自动转换

HttpError

构造函数

httpError实例的构造函数为 vFetch.HttpError

示例

{
  code: "TOKEN_EXPIRE"
  httpStatus: 401
  message: "用户认证失败"
}

整体示例

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="../dist/vFetch.js"></script>
</head>
<body>
  <script>
    console.log(window, VFetch.HttpError, VFetch.HTTP_ERROR_MAP, VFetch.httpConfig)
    const http = VFetch(VFetch.httpConfig)

    http.injectAfter(function(rst){
      console.log('injectAfter', rst)
      return new vFetch.HttpError({
        code: '001',
        message: 'error test',
        httpStatus: null,
      })
    })

    http.injectAfter(function(){
      console.log(222);
    })

    http.setErrorHook(async function(e){
      console.log(e, 'error');
      const timeoutPromise = new Promise(resolve => setTimeout(() => {
        resolve('async hook')
      }, 1000))
      const data = await timeoutPromise
      console.log(data)
    })

    http.get('t.json', {a:2, c:3}, { baseUrl, headers, timeout, ... })
      .then(rst => {
        //console.log(rst, 'success');
      }).catch(e => {
        //console.log(e, 'error');
      })
  </script> 
</body>
</html>

Keywords

FAQs

Package last updated on 27 Apr 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc