You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Next.js+Ghost API调用tryghost接口遇Axios适配器不支持错误

解决Next.js + Ghost API的Axios适配器错误

问题本质

你遇到的ERR_NOT_SUPPORT错误是因为@tryghost/content-api内置的Axios在Next.js React Server Components(RSC)环境下无法找到可用的网络请求适配器:

  • RSC环境不支持浏览器端的XHR适配器
  • 打包后的代码缺失Node.js环境的HTTP适配器
    手动安装全局axios无效,因为库内部使用的是自身打包的Axios版本,和你安装的全局包不共享。

解决方案

方案1:用Next.js内置Fetch替换Ghost SDK的Axios请求(推荐)

直接自定义请求函数,利用Next.js原生的fetch替代SDK内置的Axios,彻底绕开适配器问题:

修改你的app/ghost/post.js代码:

import GhostContentAPI from '@tryghost/content-api';

// 自定义基于fetch的请求逻辑
const customMakeRequest = async ({ url, method, headers, body }) => {
  const requestOptions = {
    method,
    headers: new Headers(headers),
    body: body ? JSON.stringify(body) : undefined
  };

  const response = await fetch(url, requestOptions);
  
  if (!response.ok) {
    throw new Error(`Ghost API请求失败: ${response.status} ${response.statusText}`);
  }

  return response.json();
};

// 初始化Ghost API客户端,传入自定义请求函数
const ghostAPI = new GhostContentAPI({
  url: process.env.GHOST_API_URL,
  key: process.env.GHOST_API_KEY,
  version: process.env.GHOST_API_VERSION || 'v5.0',
  makeRequest: customMakeRequest // 替换默认的Axios请求
});

export async function getPosts() {
  try {
    const posts = await ghostAPI.posts.browse({ limit: 10 });
    return { posts };
  } catch (error) {
    console.error('获取Ghost文章失败:', error);
    return { posts: undefined };
  }
}

方案2:调整Webpack配置强制包含Axios的Node适配器

如果一定要使用SDK内置的Axios,可以修改Next.js的Webpack配置,确保Node环境的HTTP适配器被打包:

在next.config.js中添加以下配置:

/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack: (config) => {
    // 强制使用项目安装的axios,并确保Node适配器被打包
    config.resolve.alias['axios'] = require.resolve('axios');
    config.externals = [...(config.externals || []), { 'axios': 'commonjs axios' }];
    return config;
  },
};

module.exports = nextConfig;

注意:此方法可能存在版本兼容问题,不如方案1稳定。

额外注意事项

  • 确保你的环境变量(GHOST_API_URL、GHOST_API_KEY等)已正确配置在.env.local文件中
  • 在Server Components中执行API请求时,无需担心跨域问题,因为请求是在服务端发起的

内容的提问来源于stack exchange,提问作者Ranos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 05:50:32