【问题标题】:Axios Typescript on Next.js headers type issue关于 Next.js 标头类型问题的 Axios Typescript
【发布时间】:2022-01-18 08:27:45
【问题描述】:

我使用来自 Spring Boot API 的 JWT 身份验证配置了一个 next.js 应用程序(Next 用作客户端)。所有 next.js 都是在本教程的启发下完成的: https://www.mikealche.com/software-development/how-to-implement-authentication-in-next-js-without-third-party-libraries

Axios:0.24.0 下一个:12.0.7 反应:17.0.2 驻波比:1.1.0

在像 [id].tsx 这样的页面上,我使用 axios 发出请求

const headers = api.defaults.headers;
const fetcher = (url:string)=> axios.get(url,{headers}).then(res => res.data)

const router = useRouter()
    const { id } = router.query
    const path = process.env.API_URL + "events/" + id;
    const { data } = useSWR<EventType>(path, fetcher);

... rest of the component uses "data"...and after the component...

export async function getStaticPaths() {
  return {
    paths: [
      '/events/[...id]',
    ],
    fallback: true,
  }
}

export default EventPage;

在“标题”上我遇到了打字错误:

(property) AxiosRequestConfig<any>.headers?: AxiosRequestHeaders
Type 'HeadersDefaults' is not assignable to type 'AxiosRequestHeaders'.
  Index signature for type 'string' is missing in type 'HeadersDefaults'.ts(2322)
index.d.ts(68, 3): The expected type comes from property 'headers' which is declared here on type 'AxiosRequestConfig<any>'

有一个 api.ts 文件创建了我在整个应用程序上用于所有请求的 axios 对象

import Axios from "axios";

const api = Axios.create({
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    }
});

export default api;

那个 api 是在 [id].tsx 上导入的

并且 Auth 上下文是在 auth.tsx 上创建的

import React, { createContext, useState, useContext, useEffect } from 'react'
import { useRouter } from "next/router";
import LoadingPage from '../pages/loading';
import api from '../services/api';

const AuthContext = createContext({});

export const AuthProvider = ({ children }) => {

    const [loading, setLoading] = useState<boolean>(true)

    useEffect(() => {
        async function loadUserFromStorage() {
            const token = window.localStorage.getItem('jwtAuthToken')
            if (token) {
                api.defaults.headers['Authorization'] = `Bearer ${token}`
            }
            setLoading(false)
        }
        loadUserFromStorage()
    }, [])

    return (
        <AuthContext.Provider value={{ loading }}>
            {children}
        </AuthContext.Provider>
    )
}


export const useAuth = () => useContext(AuthContext)

export const ProtectRoute = ({ children }) => {
    const auth = useAuth();
    const router = useRouter();
    if (
        (auth.loading && router.pathname !== '/') ||
        (router.pathname !== '/' && !window.localStorage.getItem('jwtAuthToken'))
    ) {
      return <LoadingPage />; 
    }
    return children;
  };

auth.loading 也有类型错误,我还不知道怎么解决。

所有这些都应用于 _app.js:

function MyApp({ Component, pageProps }) {
  return (
    <AuthProvider>
      <ProtectRoute>
        <Component {...pageProps} />
      </ProtectRoute>
    </AuthProvider>
  );
}

在开发模式下一切正常,但由于类型错误,我无法构建。

【问题讨论】:

    标签: typescript axios next.js http-headers


    【解决方案1】:

    最后,我能够从 node_modules 上的 axios 中查看 index.d.ts 来解决它。在我正在执行的每个获取(每个页面)和删除(每个带有删除图标的 Material-ui 卡)请求上,都不需要发布和放置,因为在将标题作为道具传递给表单时,类型发生了变化。

    const headers = api.defaults.headers.get;
    

    需要添加使类型兼容的方法。 对于 auth.loading,在 auth.tsx 上

    const AuthContext = createContext<{loading: boolean}>({loading: false});
    

    【讨论】:

      猜你喜欢
      • 2022-10-05
      • 2021-12-12
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多