我有一个独立的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的其他组件中,因此除非绝对必要,否则我不想对其进行重大更改。
我确实在页面本身上添加了一个上下文挂钩来调用API客户端,但这仅作为一种变通方法,因为我无法访问APIService中的标头或令牌,因为它没有上下文访问权限。 / p>
所以我可以在页面上添加类似的功能,但是我知道这是一个可怕的解决方案。
useEffect(()=> { fetchData(); },[]);