redux-api-middleware 如何对端点进行全局设置
redux-api-middleware How to do global settings for endpoint
在 redux-api-middleware
中,我们可以创建一个 API 调用,如下所示,
export function loadUsers() {
return {
[CALL_API]: {
headers: { 'Content-Type': 'application/json' },
endpoint: 'http://localhost:1337/users',
method: 'GET',
types: [LOAD_USERS_REQUEST, LOAD_USERS_SUCCESS, LOAD_USERS_FAILURE]
}
}
}
问题是,对于每个请求,我都在使用公共端点 http://localhost:1337
、Header 内容类型和授权令牌设置。
我需要一个地方来全局设置这些设置,从他们的官方文档中找不到解决方案。有人知道吗?或者有什么想法可以实现这个目标吗?
提前致谢..
在中间件中你可以获得store state的访问权限,所以你可以将token和其他auth信息放入store中,然后在中间件中使用它。
我有同样的问题,并以这样的实施结束:
const callApiMiddleware = store => next => action => {
// skip everything which is not API call
const callAPI = action[CALL_API]
if (typeof callAPI === 'undefined') {
return next(action);
}
// the session info from store
const session = store.getState().session;
// perform request
const {endpoint, headers, method} = callAPI;
return fetch(endpoint, {
headers: Object.assign({
Authorization: `Bearer ${session && session.token}`
// you can add more default headers there if you would like so
}, headers),
method
});
};
在 redux-api-middleware
中,我们可以创建一个 API 调用,如下所示,
export function loadUsers() {
return {
[CALL_API]: {
headers: { 'Content-Type': 'application/json' },
endpoint: 'http://localhost:1337/users',
method: 'GET',
types: [LOAD_USERS_REQUEST, LOAD_USERS_SUCCESS, LOAD_USERS_FAILURE]
}
}
}
问题是,对于每个请求,我都在使用公共端点 http://localhost:1337
、Header 内容类型和授权令牌设置。
我需要一个地方来全局设置这些设置,从他们的官方文档中找不到解决方案。有人知道吗?或者有什么想法可以实现这个目标吗?
提前致谢..
在中间件中你可以获得store state的访问权限,所以你可以将token和其他auth信息放入store中,然后在中间件中使用它。
我有同样的问题,并以这样的实施结束:
const callApiMiddleware = store => next => action => {
// skip everything which is not API call
const callAPI = action[CALL_API]
if (typeof callAPI === 'undefined') {
return next(action);
}
// the session info from store
const session = store.getState().session;
// perform request
const {endpoint, headers, method} = callAPI;
return fetch(endpoint, {
headers: Object.assign({
Authorization: `Bearer ${session && session.token}`
// you can add more default headers there if you would like so
}, headers),
method
});
};