npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

sd-ajax

v0.5.14

Published

基于axios的ajax业务封装,可用于 SSR

Downloads

11

Readme

sd-ajax

基于axios的ajax业务封装,可用于ssr

Installation

$ npm install sd-ajax --save

Demo

import Vue from 'vue'
import { Raven } from 'sd-raven'
import { createAxios, setAjaxDebugState } from 'sd-ajax'

// 是否开启调试
setAjaxDebugState(process.env.NODE_ENV !== 'production')

// 对返回值的处理,如接入raven日志监控等
const options = {
  handleRequestError: err => {
    Raven.captureException(err, {
      extra: {
        type: 'requestError'
      }
    })
  },
  handleResponseData: (data) => {
    Vue.sdAccount && Vue.sdAccount.interceptHttpCode(data.code)
  },
  handleResponseError: (err, config) => {
    Raven.captureException(err, {
      extra: {
        type: 'responseError',
        config
      }
    })
  },
  // 对请求数据的处理
  transformRequest: (data, headers) => {
    data.flag = '1'
    return data
  }
}

export default const api = createAxios({
  timeout: 8000, // default 15000
  baseURL: '//api.shuidichou.com',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded' // default
  }
}, options)

export const apiWave = createAxios({
  baseURL: '//wave.shuidichou.com'
}, options)

API

  • createAxios 创建一个axios实例

    createAxios(settings, options)

    settings 是axios的相关配置

    options包含5个需自定义的函数:

    • handleRequestData 接收一个requestData参数

    • handleRequestError 接收一个请求失败的err参数

    • handleResponseData

      接收一个响应成功的responseData参数和一个config参数(包含一些api的信息),useRawDatatrue时,只接收一个原始的返回值

    • handleResponseError

      接收一个响应失败的err参数一个config参数(包含一些api的信息,config可能为空),useRawDatatrue时,只接收一个原始的返回值

    • transformRequest

      可以是函数或函数数组,对请求数据的处理,接收两个参数dataheaders

      注意:get请求时,只接收一个参数data

    options还有一些可选参数:

    • AuthorizationKey (String) 默认'AuthorizationV2'
    • tokenKey (String) 默认'token'
    • ignoreErrorCode (Boolean) 是否忽略处理接口自定义错误码,默认不忽略
    • errorCodeKey (String) 自定义接口错误码字段,默认为'code'
    • errorCodeOkValue (Number|String|Array) 自定义接口错误码表示返回正确的值,默认为0
    • setHeaderAuth (Boolean) 默认true,是否设置headers Authorization
    • setBodyAuth (Boolean) 默认true,是否设置body Authorization
    • useRawData (Boolean) 是否使用原始的未经过处理的返回值,默认false
    • userDefinedResponse (Boolean) 是否允许用户返回自定义的response,默认false
    • enableTrace (Boolean) 是否开启请求头部设置 trace 相关字段,默认false
    • traceSampler (0 or 1) 在开启 trace 的基础上,设置采样开关:0为关闭; 1为开启
    • needBase64Keys (Array) 需要做base64编码的头部字段名单,默认为空数组
    • enableBase64 (Boolean) 是否开启对 needBase64Keys 中的头部值进行 base64 编码,默认false
    • getCookieFn (Function) 指定获取 Cookie 的函数,在 SSR 中非常有用,默认为内置的仅用于浏览器中获取 Cookie 的函数。

Other

通过createAxios方法生成的实例的方法说明:

get方法外,其余方法使用同axios

  • get

    .get(url, [params], [config])

    如果想使用跟axios一样的get方法,使用.rawGet替代

在mpvue小程序中的使用

配置

在webpack中配置别名:

resolve: {
  alias: {
    // ....
    'sd-ajax': 'sd-ajax/dist/sd-ajax-mini'
  }
}

用法

发送普通请求

// 发送普通 GET 请求
axios.get('https://www.url.com/api/xx')

// 发送 urlencoded 数据
axios.post('https://www.url.com/api/xx', { nickname: '233' })

// 发送 json 数据
axios.post('https://www.url.com/api/xx', { nickname: '233' }, {
  headers: {
    'Content-Type': 'application/json'
  }
})

上传文件

如果在 POST 请求的数据中出现了 $upload 字段,则将此请求视为上传文件请求

axios.post('https://www.url.com/api/xx', {
  $upload: {
    name: 'avatar',
    filePath: 'wxfile://sometempfilepath'     // 来自 wx.chooseImage 等接口的结果
  },
  // ...其它一起发送的数据
})

下载文件

如果在一个 GET 请求中 responseTypefile, 则将此请求视为下载文件请求. 返回文件的临时路径 (详见小程序开发文档)

注意: 只有此时可以使用 http 协议

axios.get('http://www.url.com', { responseType: 'file' }).then(response => {
  console.log(response.data)    // 输出下载成功的文件的临时路径
})

不支持的选项

注:由于小程序的请求功能有限, 所以不支持以下选项. 如果使用时出现了以下选项, 将直接忽略. 不在此列表中的功能均可使用

  • timeout
  • withCredentials
  • auth
  • xsrfCookieName
  • xsrfHeaderName
  • onUploadProgress
  • onDownloadProgress
  • maxContentLength
  • maxRedirects
  • httpAgent
  • httpsAgent
  • proxy

受限的选项

  • url: 必须指定协议, 并且只能是 http 或 https. 只有下载文件可以用 http
  • method: 只能是小程序支持的方法 (详见小程序开发文档)
  • responseType: 只能是 json, text, file 中的一个