百科.dev
全部条目AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
R

redux-api-middleware

> 编程语言
开源

用于调用 API 的 Redux 中间件。

1.5K stars0 点赞1 次浏览
访问官网GitHub

工具介绍

用于调用 API 的 Redux 中间件。

redux-api-middleware

Redux middleware for calling an API.

This middleware receives Redux Standard API-calling Actions (RSAAs) and dispatches Flux Standard Actions (FSAs) to the next middleware.

RSAAs are identified by the presence of an [RSAA] property, where RSAA is a String constant defined in, and exported by redux-api-middleware. They contain information describing an API call and three different types of FSAs, known as the request, success and failure FSAs.


Table of contents

  • Introduction
    • Breaking Changes in 2.0 Release
    • Breaking Changes in 3.0 Release
  • Installation
    • configureStore.js
    • app.js
  • Usage
    • Defining the API call
      • endpoint
      • method
      • body
      • headers
      • options
      • credentials
      • fetch
    • Bailing out
    • Lifecycle
    • Customizing the dispatched FSAs
    • Dispatching Thunks
    • Testing
  • Reference
    • Request type descriptors
    • Success type descriptors
    • Failure type descriptors
    • Exports
      • createAction
      • RSAA
      • apiMiddleware
      • createMiddleware(options)
      • isRSAA(action)
      • validateRSAA(action)
      • isValidRSAA(action)
      • InvalidRSAA
      • InternalError
      • RequestError
      • ApiError
      • getJSON(res)
    • Flux Standard Actions
      • type
      • payload
      • error
      • meta
    • Redux Standard API-calling Actions
      • [RSAA]
      • endpoint
      • method
      • body
      • headers
      • options
      • credentials
      • bailout
      • fetch
      • ok
      • types
      • Type descriptors
  • History
  • Tests
  • Upgrading from v1.0.x
  • Upgrading from v2.0.x
  • License
  • Projects using redux-api-middleware
  • Acknowledgements

Introduction

The following is a minimal RSAA action:

import { createAction } from `redux-api-middleware`;

createAction({
  endpoint: 'http://www.example.com/api/users',
  method: 'GET',
  types: ['REQUEST', 'SUCCESS', 'FAILURE']
})

Upon receiving this action, redux-api-middleware will

  1. check that it is indeed a valid RSAA action;

  2. dispatch the following request FSA to the next middleware;

    {
      type: 'REQUEST'
    }
    
  3. make a GET request to http://www.example.com/api/users;

  4. if the request is successful, dispatch the following success FSA to the next middleware;

    {
      type: 'SUCCESS',
      payload: {
        users: [
          { id: 1, name: 'John Doe' },
          { id: 2, name: 'Jane Doe' },
        ]
      }
    }
    
  5. if the request is unsuccessful, dispatch the following failure FSA to the next middleware.

    {
      type: 'FAILURE',
      payload: error // An ApiError object
      error: true
    }
    

We have tiptoed around error-handling issues here. For a thorough walkthrough of the redux-api-middleware lifecycle, see Lifecycle below.

Breaking Changes in 2.0 Release

See the 2.0 Release Notes, and Upgrading from v1.0.x for details on upgrading.

Breaking Changes in 3.0 Release

See the 3.0 Release Notes, and Upgrading from v2.0.x for details on upgrading.

Installation

redux-api-middleware is available on npm.

$ npm install redux-api-middleware --save

To use it, wrap the standard Redux store with it. Here is an example setup. For more information (for example, on how to add several middlewares), consult the Redux documentation.

Note: redux-api-middleware depends on a global Fetch being available, and may require a polyfill for your runtime environment(s).

configureStore.js

import { createStore, applyMiddleware, combineReducers } from 'redux';
import { apiMiddleware } from 'redux-api-middleware';
import reducers from './reducers';

const reducer = combineReducers(reducers);
const createStoreWithMiddleware = applyMiddleware(apiMiddleware)(createStore);

export default function configureStore(initialState) {
  return createStoreWithMiddleware(reducer, initialState);
}

app.js

const store = configureStore(initialState);

Usage

Defining the API call

You can create an API call by creating an action using createAction and passing the following options to it.

endpoint (Required)

The URL endpoint for the API call.

It is usually a string, be it a plain old one or an ES2015 template string. It may also be a function taking the state of your Redux store as its argument, and returning such a string.

method (Required)

The HTTP method for the API call.

It must be one of the strings GET, HEAD, POST, PUT, PATCH, DELETE or OPTIONS, in any mixture of lowercase and uppercase letters.

body

The body of the API call.

redux-api-middleware uses the Fetch API to make the API call. body should hence be a valid body according to the fetch specification. In most cases, this will be a JSON-encoded string or a FormData object.

It may also be a function taking the state of your Redux store as its argument, and returning a body as described above.

headers

The HTTP headers for the API call.

It is usually an object, with the keys specifying the header names and the values containing their content. For example, you can let the server know your call contains a JSON-encoded string body in the following way.

createAction({
  // ...
  headers: { 'Content-Type': 'application/json' }
  // ...
})

It may also be a function taking the state of your Redux store as its argument, and returning an object of headers as above.

options

The fetch options for the API call. What options are available depends on what fetch implementation is in use. See MDN fetch or node-fetch for more information.

It is usually an object with the options keys/values. For example, you can specify a network timeout for node.js code in the following way.

createAction({
  // ...
  options: { timeout: 3000 }
  // ...
})

It may also be a function taking the state of your Redux store as its argument, and returning an object of options as above.

credentials

Whether or not to send cookies with the API call.

It must be one of the following strings:

  • omit is the default, and does not send any cookies;
  • same-origin only sends cookies for the current domain;
  • include always send cookies, even for cross-origin calls.

fetch

A custom Fetch implementation, useful for intercepting the fetch request to customize the response status, modify the response payload or skip the request altogether and provide a cached response instead.

If provided, the fetch option must be a function that conforms to the Fetch API. Otherwise, the global fetch will be used.

Examples:

Modify a response payload and status
…
Modify a response status based on response json
createAction({
  // ...
  fetch: async (...args) => {
    const res = await fetch(...args);
    const returnRes = res.clone(); // faster then above example with JSON.stringify
    const json = await res.json(); // we need json just to check status

    returnRes.status = json.error ? 500 : 200;

    return returnRes;
  }
  // ...
})
Skip the request in favor of a cached response
createAction({
  // ...
  fetch: async (...args) => {
    const cached = await getCache('someKey');

    if (cached) {
      // where `cached` is a JSON string: '{"foo": "bar"}'
      return new Response(cached,
        {
          status: 200,
          headers: {
            'Content-Type': 'application/json'
          }
        }
      );
    }

    // Fetch as usual if not cached
    return fetch(...args);
  }
  // ...
})

Bailing out

In some cases, the data you would like to fetch from the server may already be cached in your Redux store. Or you may decide that the current user does not have the necessary permissions to make some request.

You can tell redux-api-middleware to not make the API call through bailout property. If the value is true, the RSAA will die here, and no FSA will be passed on to the next middleware.

A more useful possibility is to give bailout a function. At runtime, it will be passed the state of your Redux store as its only argument, if the return value of the function is true, the API call will not be made.

Lifecycle

The types property controls the output of redux-api-middleware. The simplest form it can take is an array of length 3 consisting of string constants (or symbols), as in our example above. This results in the default behavior we now describe.

  1. When redux-api-middleware receives an action, it first checks whether it has an [RSAA] property. If it does not, it was clearly not intended for processing with redux-api-middleware, and so it is unceremoniously passed on to the next middleware.

  2. It is now time to validate the action against the RSAA definition. If there are any validation errors, a request FSA will be dispatched (if at all possible) with the following properties:

    • type: the string constant in the first position of the types array;
    • payload: an InvalidRSAA object containing a list of said validation errors;
    • error: true.

redux-api-middleware will perform no further operations. In particular, no API call will be made, and the incoming RSAA will die here.

  1. Now that redux-api-middleware is sure it has received a valid RSAA, it will try making the API call. If everything is alright, a request FSA will be dispatched with the following property:
  • type: the string constant in the first position of the types arr

GitHub Issues· 52 开放

在 GitHub 查看全部
  • #187

    Feature Request: abort request with AbortController signal

    enhancementhelp wanted更新于 2021年11月19日
  • #267

    Please don't deprecate the RSAA constant

    更新于 2021年11月2日
  • #230

    Is this repository maintained?

    更新于 2021年10月26日

核心特点

  • •Introduction
  • •Breaking Changes in 2.0 Release
  • •Breaking Changes in 3.0 Release
  • •Installation
  • •configureStore.js
  • •Defining the API call
  • •endpoint
  • •credentials
  • •Bailing out
  • •Lifecycle

> 标签

JavaScript

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言