登录nextjs后添加默认的axios header

问题描述 投票:0回答:2

我正在为我的应用程序使用 Next.js,并且当前有一个将 JWT 设置为 cookie 的 API 路由。在整个应用程序中,我使用 Axios 从外部 API 获取所有数据,并且在用户登录后,我需要将该 cookie 设置为每个 API 调用的默认请求标头,以确保用户已通过身份验证。基本流程是这样的:

登录表单向我的 API 路径

/api/auth/login
发送一个 post 请求,传递用户名和密码并返回 JWT,并将其设置为 cookie。设置
idToken
cookie 后,我需要将其作为身份验证标头添加到我的 Axios 实例中的每个 API 请求中,如此处的
adapter
所示。我怎样才能完成这件事?

我的手柄登录功能:

const handleLogin = async (values: ValuesProps) => {
    const response = await axios.post('/api/auth/login', values);

    if (response.status !== 200) {
      throw new Error(response.statusText);
    }
};

这与

api/auth/login
:

import { NextApiRequest, NextApiResponse } from 'next';
import { setCookie, parseCookies } from 'nookies';
import { adapter } from 'utils/api/config';

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  if (req.method !== 'POST') {
    res.status(500).json('Only POST requests allowed at this route.');
  } else {
    const { data } = await adapter.post(AUTH.login, JSON.stringify(req.body));
    const cookies = parseCookies();

    setCookie({ res }, 'idToken', data.token, {
      maxAge: 30 * 24 * 60 * 60,
      path: '/',
    });

    api.defaults.headers.Authorization = `Bearer ${cookies['idToken']}`

    res.status(200).json(data);
  }
};

export default handler;

正如您在此处看到的,我尝试添加

adapter.defaults.headers.Authorization
作为全局默认值,但我没有在请求标头中看到它。在全球范围内进行设置的最佳方法是什么?

javascript reactjs next.js axios
2个回答
2
投票

您可以使用

axios.create
。它是一个创建 axios 新实例的工厂。 看起来像这样:

import axios from "axios";

export const axiosInstance = async () => {
  // You need to be careful in next.js for adding cookies.
  // You could be on the server or a client. This code will work for the client assuming you will use it on the client side.
  // I believe you are using `parser` to get cookies. get the token.
  const yourToken = "whatever";
  const axiosClient = axios.create({
      baseURL: 'baseUrlHere',
      timeout: 1000,
      headers: {
          'Accept': 'application/vnd.GitHub.v3+json',
          // This is how u set in your code
          'Authorization': `Bearer ${cookies['idToken']}`
      }
   });

   return axiosClient;
}

然后将其导入到您想要使用它的任何地方:

 const { data } = await axiosInstance().post("/auth");

从技术上讲,这应该可行。


-1
投票

您可以通过命令为所有 axios 请求设置默认标头:

const token = getCookie('token')
axios.defaults.headers.common["idToken"] = token
© www.soinside.com 2019 - 2024. All rights reserved.