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

Arn*_*auf 17 api reactjs axios next.js

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

该API工作正常,但无论我如何努力实现内部的我爱可信电话getServerSideProps,我总是得到同样的错误,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: ''
    },
  }
}
Run Code Online (Sandbox Code Playgroud)

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)
  })
}
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)

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

Ary*_*hur 11

不要使用 axios。只需使用fetch().

Next.jsfetch()默认情况下在客户端和服务器上都会填充,因此您可以直接使用它:

除了fetch()客户端之外,Next.js 还可以fetch()在 Node.js 环境中进行填充。您可以在服务器代码中使用fetch()(例如getStaticProps/ ),而无需使用诸如或 之getServerSideProps类的 Polyfill 。isomorphic-unfetchnode-fetch

来源