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

@alova/adapter-xhr

v1.0.6

Published

XMLHttpRequest adapter for alova.js

Downloads

525

Readme

@alova/adapter-xhr

alova 的 XMLHttpRequest 适配器

npm build coverage status typescript license

官网 | 核心库 alova

安装

npm install @alova/adapter-xhr --save

使用方法

创建 alova

使用 xhrRequestAdapter 作为 alova 的请求适配器。

import { createAlova } from 'alova';
import { xhrRequestAdapter } from '@alova/adapter-xhr';

const alovaInst = createAlova(
  // ...
  requestAdapter: xhrResponseAdapter(),
  // ...
);

请求

XMLHttpRequest 适配器提供了基本的配置参数,包含responseTypewithCredentialsmimeTypeauth,具体如下:

const list = () =>
	alovaInst.Get('/list', {
		/**
		 * 设置响应数据类型
		 * 可以设置更改响应类型。 值为:“arraybuffer”、“blob”、“document”、“json”和“text”
		 * 默认为“json”
		 */
		responseType: 'text',

		/**
		 * 当凭证要包含在跨源请求中时为true。 当它们被排除在跨源请求中以及当 cookie 在其响应中被忽略时为 false。 默认为false
		 */
		withCredentials: true,

		/**
		 * 设置响应数据的mimeType
		 */
		mimeType: 'text/plain; charset=x-user-defined',

		/**
		 * auth 表示使用 HTTP Basic 身份验证,并提供凭据。
		 * 这将设置一个 `Authorization` 标头,覆盖任何现有的
		 * 使用 `headers` 设置的 `Authorization` 自定义标头。
		 * 请注意,只有 HTTP Basic 身份验证可以通过此参数进行配置。
		 * 对于 Bearer 令牌等,请改用 `Authorization` 自定义标头。
		 */
		auth: {
			username: 'name1',
			password: '123456'
		}
	});
const { loading, data } = useRequest(list);
// ...

上传

使用FormData上传文件,这个FormData实例会通过xhr.send发送到服务端。

const uploadFile = imageFile => {
	const formData = new FormData();
	formData.append('file', imageFile);
	return alovaInst.Post('/uploadImg', formData, {
		// 开启上传进度
		enableUpload: true
	});
};

const {
	loading,
	data,
	uploading,
	send: sendUpload
} = useRequest(uploadFile, {
	immediate: false
});

// 图片选择事件回调
const handleImageChoose = ({ target }) => {
	sendUpload(target.files[0]);
};

下载

将请求 url 指向文件地址即可下载,你也可以通过将enableDownload设置为 true 来开启下载进度。

const downloadFile = () =>
	alovaInst.Get('/bigImage.jpg', {
		// 开启下载进度
		enableDownload: true,
		responseType: 'blob'
	});

const { loading, data, downloading, send, onSuccess } = useRequest(downloadFile, {
	immediate: false
});
onSuccess(({ data: imageBlob }) => {
	// 下载图片
	const anchor = document.createElement('a');
	anchor.href = URL.createObjectURL(blob);
	anchor.download = 'image.jpg';
	anchor.click();
	URL.revokeObjectURL(anchor.href);
});
const handleImageDownload = () => {
	send();
};

模拟请求适配器兼容

在开发应用时,我们仍然可能需要用到模拟请求。只是默认情况下,模拟请求适配器(@alova/mock)的响应数据是一个Response实例,即默认兼容GlobalFetch请求适配器,当使用 XMLHttpRequest 适配器时,我们需要让模拟请求适配器的响应数据适配 XMLHttpRequest 适配器,此时你需要使用**@alova/adapter-xhr**包中导出的xhrMockResponse作为响应适配器。

import { defineMock, createAlovaMockAdapter } from '@alova/mock';
import { xhrRequestAdapter, xhrMockResponse } from '@alova/adapter-xhr';

const mocks = defineMock({
	// ...
});

// 模拟数据请求适配器
export default createAlovaMockAdapter([mocks], {
	// 指定请求适配器后,未匹配模拟接口的请求将使用这个适配器发送请求
	httpAdapter: xhrRequestAdapter(),

	// 使用xhrMockResponse,让模拟数据适配XMLHttpRequest适配器
	onMockResponse: xhrMockResponse
});

export const alovaInst = createAlova({
	// ...
	// 通过环境变量控制是否使用模拟请求适配器
	requestAdapter: process.env.NODE_ENV === 'development' ? mockAdapter : xhrRequestAdapter()
});