检查完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
相关产品推荐
相关产品推荐

