You need to enable JavaScript to run this app. 检查完index.tsx所有缩进,导出getServerSideProps时触发语法报错
优惠活动
大模型
产品
解决方案
定价
更多

检查完index.tsx所有缩进,导出getServerSideProps时触发语法报错

getServerSideProps 导出语法报错修复

错误根因

  • 该问题和缩进格式完全无关,核心是ES模块导出语法使用错误
  • 错误写法export getServerSideProps = async (ctx) => {} 属于将模块导出声明和变量赋值逻辑混写,JS解析器识别到export关键字后,后续合法的起始标识应为default、命名导出包裹符{、模块通配符*,直接跟函数名的写法完全不符合语法规范,因此抛出“Unexpected token, expected "{"”的解析错误。

合规修复方案

Next.js 中getServerSideProps的合法导出写法有两种:

  • 最常用的直接导出写法:在函数定义前增加const关键字作为变量声明前缀
    export const getServerSideProps = async (ctx) => {
      const categories = await fetch(`http://localhost:8080/api/v1/mt/categories`);
      return {
        categoryOptions: await categories.json()
      }
    }
    
  • 先定义函数、后单独导出的写法
    async function getServerSideProps(ctx) {
      const categories = await fetch(`http://localhost:8080/api/v1/mt/categories`);
      return {
        categoryOptions: await categories.json()
      }
    }
    export { getServerSideProps }
    

附带优化建议

  • 原代码中fetch请求URL末尾多余的?、return语句外层无意义的圆括号不属于语法错误,但会带来不必要的冗余,可一并清理减少代码噪音。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 17:15:03