vj-ajax

0.0.6 • Public • Published

vj-ajax

fetchAPI的简单封装

安装

使用 npm:

$ npm i vj-ajax -S

示例

发起一个 GET 请求

import ajax from 'vj-ajax';

// 简单的get请求,url直接当作参数传入
ajax('/xxx?id=123').then(res => {
  console.log(res);
}.catch(error => {
  console.error(error);
});

// 带参数,且比较多的get请求,写法和jquery的ajax较为相近
ajax({
  url: 'xxx',
  data: {
    id: 123,
    name: 'vj',
  },
}).then(res => {
  console.log(res);
}.catch(error => {
  console.error(error);
});

发起一个 POST 请求

import ajax from 'vj-ajax';

// 参数位于query的POST请求
ajax({
  url: 'xxx',
  type: 'POST', // 添加请求类型post,大小写均可
  data: {
    id: 123,
    name: 'vj',
  },
}).then(res => {
  console.log(res);
}.catch(error => {
  console.error(error);
});

// 参数位于body的POST请求
ajax({
  url: 'xxx',
  type: 'POST',
  contentType: 'JSON', // 添加contentType类型为json,大小写均可
  data: {
    id: 123,
    name: 'vj',
  },
}).then(res => {
  console.log(res);
}.catch(error => {
  console.error(error);
});

发起一个发送 文件POST 请求

import ajax from 'vj-ajax';

// 发送文件
let formData = new FormData();
formData.append('file', file);
ajax({
  url: 'xxx',
  type: 'POST',
  contentType: 'FORMDATA', // 添加contentType类型为formdata,大小写均可
  data: formData,
}).then(res => {
  console.log(res);
}.catch(error => {
  console.error(error);
});

PUT、DELETE 方法等同POST方法

vj-ajax API(设置vj-ajax全局参数)

现阶段支持三个全局参数

import { ajax } from 'vj-ajax';

// 推荐在入口文件全局设置
ajax.config({
  signRedirect: '',  // 全局,禁止访问message信号
  redirect: 'https://www.51vj.cn/login', // 全局,禁止范围(登陆过期)转跳地址
  params: { // 全局url带参,设置后所有请求都会在带上这些参数,参数位于query
    appid: 2,
  },
});

Readme

Keywords

none

Package Sidebar

Install

npm i vj-ajax

Weekly Downloads

1

Version

0.0.6

License

ISC

Last publish

Collaborators

  • webrischa