javascript 使用Redux中间件将Authorization标头注入到redux-api-middleware请求中。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 使用Redux中间件将Authorization标头注入到redux-api-middleware请求中。相关的知识,希望对你有一定的参考价值。

import { CALL_API } from 'redux-api-middleware'

export function fetchLocations() {
  return {
    [CALL_API]: {
      endpoint: 'http://api.somesite.com/api/locations',
      method: 'GET',
      // Don't have to manually add the Authorization header to every request.
      headers: { 'Content-Type': 'application/json' },
      types: ['REQUEST', 'SUCCESS', 'FAILURE']
    }
  }
}
// ...Likely some other imports such as React etc.

import { createStore, applyMiddleware } from 'redux'
import { apiMiddleware } from 'redux-api-middleware'

// Our custom middleware.
import apiAuthInjector from './apiAuthInjector'

const store = createStore(
  reducers,
  applyMiddleware(
    apiAuthInjector, // Put it somewhere before `apiMiddleware`.
    apiMiddleware,
  )
)

// ...the rest of your app setup.
import { CALL_API } from 'redux-api-middleware'
import ls from 'local-storage'

export default function() {
  return function(next) {
    return function(action) {
      const callApi = action[CALL_API]

      // Check if this action is a redux-api-middleware action.
      if (callApi) {
        // Inject the Authorization header from localStorage.
        callApi.headers = Object.assign({}, callApi.headers, {
          Authorization: ls.get('id_token') || '',
        })
      }

      // Pass the FSA to the next action.
      return next(action)
    }
  }
}

以上是关于javascript 使用Redux中间件将Authorization标头注入到redux-api-middleware请求中。的主要内容,如果未能解决你的问题,请参考以下文章

javascript AngularJS Redux中间件

javascript Redux可观察中间件

Store在Redux中的意义是啥?

Redux 中间件和 GraphQL

将 redux-devtools 传递给带有中间件的 redux 存储

Redux+Websockets:为啥要使用中间件来管理这个?