如何在 NextJS 的 getServerSideProps 函数内从 Axios 获取 API 数据?

时间:2021-01-18 15:28:21

标签: reactjs api axios next.js

我正在使用 Next.js 构建一个应用程序,我的工作是连接到特定的 API 路由(使用 API 平台设置)并使用路由响应填充页面。

API 工作正常,但无论我如何努力在 getServerSideProps 内实现我的 axios 调用,我总是从我的 Node 堆栈中得到相同的错误 (ECONNREFUSED)。

相反,我选择从 useEffect() 获取数据并且它工作正常,但我想知道是否可以直接在 getServerSideProps 中调用它。

我正在为 Docker 使用 Node 容器,并且路由通过 JWT 令牌(存储在会话和服务器端连接的客户端 cookie 中)进行身份验证

详情如下:

pages/accounts.js

export async function getServerSideProps(context) {
  const cookies = new Cookies(context.req.headers.cookie)
  const adminToken = cookies.get('jwtToken')

  const res = await getAllAccounts(adminToken)

  return {
    props: {
      testdata: ''
    },
  }
}

lib/accounts.js

import service from '../service'

export const getAllAccounts = async (adminToken) => {
  const res = service({ jwtToken : adminToken }).get(`/accounts`).then((response) => {
  
  }).catch((error) => {
    console.dir(error)
  })
}

http 包装器

import axios from 'axios';
import jwt_decode from "jwt-decode";
import mockAdapter from 'axios-mock-adapter';

const service = ({ jwtToken = null, store = null, mockURL = null, mockResponse = null, multipart = false } = {}) => {
  const options = {};

  options.baseURL = process.env.NEXT_PUBLIC_API_URL + '/api';

  if(multipart === true) {
    options.headers = {
      'Content-Type': 'multipart/form-data'
    }
  } else {
    options.headers = {
      'Content-Type': 'application/ld+json',
      accept: 'application/ld+json'
    }
  }

  const instance = axios.create(options);

  instance.interceptors.response.use(response => {
    return response;
  }, error => {
    return Promise.reject(error);
  })

  if (mockURL !== null && mockResponse !== null) {
    let mock = new mockAdapter(instance);
    mock.onAny(mockURL).reply(200, mockResponse)
  }

  return instance;
};

export default service;

通过节点堆栈中的错误转储,我设法看到请求标头正确,并且 JWT 正确通过。

1 个答案:

答案 0 :(得分:0)

jwtToken 传递给服务后,您没有将其用于任何用途。

在行 const instance = axios.create(options); 之前添加如下内容:

if (jwtToken !== null) {
  options.headers.Authorization = `Bearer ${jwtToken}`
}