It is well known that the most widely used HTTP client on the browser side and node.js side is Axios. It’s a Promise based HTTP client for browsers and Node.js, but it’s not the star of the show.

The origin of

Axios’s predecessor is actually AngularJS’s $HTTP service.

To avoid confusion, it’s important to clarify that AngularJS is not Angular. AngularJS refers specifically to angular.js v1.x, while Angular refers specifically to Angular v2+ (without.js) and its set of toolchains.

This may not be a serious statement, but Axios is inspired by the $HTTP service provided in AngularJS. Ultimately, Axios is meant to provide a sort of standalone service that can be used outside of AngularJS.

The development of

Instead of using the $HTTP service, Angular uses RXJS to design a more advanced, modern, responsive HTTP client. In a responsive HTTP Client, instead of sending a Promise, we receive an Observable from RXJS, which we can subscribe to and listen for the response:

const observable = http.get('url');
observable.subscribe(o= > console.log(o));
Copy the code

Please refer to the official documentation for its basic form and detailed usage.

The body of the

@ngify/ HTTP is a responsive HTTP client shaped like Angular HttpClient. The goal of @ngify/ HTTP is similar to axios: to provide a quasi-stand-alone service that can be used outside of Angular.

@ngify/ HTTP provides the following main features:

  • The ability to request typed response objects.
  • Simplified error handling.
  • Request and response interception mechanisms.
  • Default support but not limitedXMLHttpRequestFetch APIWechat applets.

A prerequisite for

Before using @ngify/ HTTP, you should have a basic understanding of the following:

  • JavaScript/TypeScript programming.
  • The usage of THE HTTP protocol.
  • RxJS Observable related technologies and operators. See the guide to Observables.

API

For a complete API definition, visit ngify.github. IO /ngify.

reliability

@ngify/ HTTP uses and passes the Angular HttpClient unit test (the test code is modified for minor API differences).

The installation

npm i @ngify/http
Copy the code

Basic usage

import { HttpClient, HttpContext, HttpContextToken, HttpHeaders, HttpParams } from '@ngify/http';
import { filter } from 'rxjs';

const http = new HttpClient();

http.get<{ code: number.data: any.msg: string} > ('url'.'k=v').pipe(
  filter(({ code }) = > code === 0)
).subscribe(res= > console.log(res));

http.post('url', { k: 'v' }).subscribe(res= > console.log(res));

const HTTP_CACHE_TOKEN = new HttpContextToken(() = > 1800000);

http.put('url'.null, {
  context: new HttpContext().set(HTTP_CACHE_TOKEN)
}).subscribe(res= > console.log(res));

http.patch('url'.null, {
  params: { k: 'v' }
}).subscribe(res= > console.log(res));

http.delete('url'.new HttpParams('k=v'), {
  headers: new HttpHeaders({ Authorization: 'token' })
}).subscribe(res= > console.log(res));
Copy the code

Intercept requests and responses

With interception, you can declare interceptors that examine and transform HTTP requests from your application to the server. These interceptors can also examine and transform the response from the server on the way back to the application. Multiple interceptors form a bidirectional linked list of request/response handlers.

@ngify/ HTTP applies interceptors in the order in which you provide them.

import { HttpClient, HttpHandler, HttpRequest, HttpEvent, HttpInterceptor } from '@ngify/http';
import { Observable, map } from 'rxjs';

const http = new HttpClient([
  new class implements HttpInterceptor {
    intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
      // Clone the request to modify the request parameters
      request = request.clone({
        headers: request.headers.set('Authorization'.'token')});returnnext.handle(request); }}, {intercept(request: HttpRequest<unknown>, next: HttpHandler) {
      request = request.clone({
        params: request.params.set('k'.'v')});console.log('Intercepted request', request);

      return next.handle(request).pipe(
        tap(response= > console.log('Intercept response', response)) ); }}]);Copy the code

While interceptors have the ability to change requests and responses, the attributes of HttpRequest and HttpResponse instances are read-only, making them essentially immutable.

There is good reason to make them immutable: the application may retry sending a request many times before it succeeds, which means that the list of interceptors may process the same request multiple times.

If the interceptor can modify the original request object, the retry phase starts with the modified request, not the original request. This immutability ensures that the interceptors see the same original request every time they try again.

If you need to modify a request, make a clone of it, modify the clone and pass it to next.handle().

Replace the HTTP request class

@ngify/ HTTP has the following HTTP request classes built in:

The HTTP request class describe
HttpXhrBackend useXMLHttpRequestMaking HTTP requests
HttpFetchBackend useFetch APIMaking HTTP requests
HttpWxBackend inWechat appletsTo make HTTP requests

HttpXhrBackend is used by default. You can change the configuration to another HTTP request class:

import { HttpFetchBackend, HttpWxBackend, setupConfig } from '@ngify/http';

setupConfig({
  backend: new HttpFetchBackend()
});
Copy the code

You can also use a custom HttpBackend implementation class:

import { HttpBackend, HttpClient, HttpRequest, HttpEvent, setupConfig } from '@ngify/http';
import { Observable } from 'rxjs';

// The HttpBackend interface is required
class CustomHttpBackend implements HttpBackend {
  handle(request: HttpRequest<any>): Observable<HttpEvent<any> > {// ...
  }
}

setupConfig({
  backend: new CustomHttpBackend()
});
Copy the code

If you need to configure HttpBackend separately for an HttpClient, you can pass the second argument to the HttpClient constructor:

const http = new HttpClient(null.new CustomHttpBackend())
Copy the code

Used in Node.js

By default, @ngify/ HTTP uses the XMLHttpRequest and Fetch APIS implemented by the browser. To use it in Node.js, you need to do the following:

XMLHttpRequest

If you need to use XMLHttpRequest in a Node.js environment, you can use XHR2, which implements the W3C XMLHttpRequest specification on the Node.js API. To use xHR2, you create a factory function that returns an XMLHttpRequest instance and passes it as a parameter to the HttpXhrBackend constructor:

import { HttpXhrBackend, setupConfig } from '@ngify/http';
import * as xhr2 from 'xhr2';

setupConfig({
  backend: new HttpXhrBackend(() = > new xhr2.XMLHttpRequest())
});
Copy the code

Fetch API

If you need to use the Fetch API in a Node.js environment, you can use node-fetch and abort controller. To apply them, you need to add them separately to Node.js’s global:

import fetch from 'node-fetch';
import AbortController from 'abort-controller';
import { HttpFetchBackend, HttpWxBackend, setupConfig } from '@ngify/http';

global.fetch = fetch;
global.AbortController = AbortController;

setupConfig({
  backend: new HttpFetchBackend()
});
Copy the code

Passing extra parameters

To keep the API consistent, you need to pass some additional parameters through the HttpContext.

Fetch API extra parameters

import { HttpContext, FETCH_TOKEN } from '@ngify/http';

// ...

// The Fetch API allows cross-domain requests
http.get('url'.null, {
  context: new HttpContext().set(FETCH_TOKEN, {
    mode: 'cors'.// ...})});Copy the code

Wechat applet extra parameters

import { HttpContext, WX_UPLOAD_FILE_TOKEN, WX_DOWNLOAD_FILE_TOKEN, WX_REQUSET_TOKEN } from '@ngify/http';

// ...

// Open HTTP2
http.get('url'.null, {
  context: new HttpContext().set(WX_REQUSET_TOKEN, {
    enableHttp2: true,})});// Upload wechat applets
http.post('url'.null, {
  context: new HttpContext().set(WX_UPLOAD_FILE_TOKEN, {
    filePath: 'filePath'.fileName: 'fileName'})});// download wechat applets
http.get('url'.null, {
  context: new HttpContext().set(WX_DOWNLOAD_FILE_TOKEN, {
    filePath: 'filePath'})});Copy the code

More and more

For more usage, visit angular.cn.