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

Next.js + React Three Fiber加载GLB模型出现URL解析错误

问题描述

使用React Three Fiber + Next.js开发网页游戏,从public文件夹加载GLB模型,模型能正常显示但控制台抛出URL解析错误,已添加'use client'指令。

错误信息:

error TypeError: Failed to parse URL from /Game_Assets/models/naturescene/naturescene.glb
    at new Promise (<anonymous>)
    at Array.map (<anonymous>)
    at Game (./app/Game/page.tsx:49:86)

加载代码:

const naturemodel = useLoader(
    GLTFLoader,
    "/Game_Assets/models/naturescene/naturescene.glb"
);
解决方案
  1. 构造浏览器端可识别的完整URL
    Next.js App Router的服务端预渲染阶段,直接使用绝对路径可能导致URL解析异常。可以通过window.location.origin拼接完整URL:
'use client';
import { useLoader } from '@react-three/fiber';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

export default function Game() {
  const modelUrl = new URL('/Game_Assets/models/naturescene/naturescene.glb', window.location.origin).href;
  const naturemodel = useLoader(GLTFLoader, modelUrl);

  return (
    <mesh>
      <primitive object={naturemodel.scene} />
    </mesh>
  );
}
  1. 改用useGLTF钩子(推荐)
    React Three Fiber的@react-three/drei库提供了useGLTF钩子,它会自动适配Next.js的路径规则,避免URL解析问题:
'use client';
import { useGLTF } from '@react-three/drei';

export default function Game() {
  const naturemodel = useGLTF('/Game_Assets/models/naturescene/naturescene.glb');

  return (
    <mesh>
      <primitive object={naturemodel.scene} />
    </mesh>
  );
}
  1. 检查路径大小写一致性
    确保public文件夹内的文件/文件夹名称大小写,和代码中的路径完全匹配。部分部署环境(如Vercel)对路径大小写敏感,可能触发解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 08:27:33