我有一个独立的APIService.js,可在我的NextJS应用程序中使用它,它可以执行一些操作,但是主要是设置BASE_URL以及用户是否已登录(应该在cookie或标头cookie-然后将其分派到redux)。
基本上,我认为我都需要此APIService;检测机器上是否有cookie(确实存在)或服务器端是否已渲染,并从标头中获取它;或者我认为更好的方法是-监听redux的更改,并从redux存储中获取令牌。
这是我的APIService;
import axios from 'axios';
import { Cookies } from 'react-cookie';
import { API_URL } from './constants';
const config = {
baseURL: API_URL,
};
const cookies = new Cookies();
const APIService = axios.create(config);
APIService.interceptors.request.use((request) => {
const token = cookies.get('token');
request.headers.Authorization = token ? `Bearer ${token}` : '';
return request;
});
export default APIService;
给出NextJS页面用法的示例;
我在_app.js中具有此功能
static async getInitialProps({ Component, ctx }) {
if (ctx.isServer) {
if (ctx.req.headers.cookie) {
const token = getCookie('token', ctx.req);
console.log('WHOAMI ', token);
ctx.store.dispatch(reauthenticate(token));
}
} else {
const { token } = ctx.store.getState().authentication;
console.log('WHOAMI2 ', token);
ctx.store.dispatch(reauthenticate(token));
}
return {
pageProps: Component.getInitialProps
? await Component.getInitialProps(ctx)
: {},
};
}
我是否需要将APIService连接()到Redux-如果可以,我该怎么办?我通常将APIService导入需要使用API的其他组件中,因此除非绝对必要,否则我不想对其进行重大更改。
在我们的应用程序中,我们所做的是使服务(尤其是身份验证服务)与Redux分离。