Encountered an unexpected GLTF import error in three.js due to invalid JSON syntax containing tokens like '<' and "<!DOCTYPE "

Whilst attempting to import my very first .gltf model into three.js using the Parcel bundler, I encountered a black screen and the following error message:

SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
    at JSON.parse (<anonymous>)
    at GLTFLoader.parse (GLTFLoader.js:315:21)
    at Object.onLoad (GLTFLoader.js:205:11)
    at three.module.js:39951:38

Here are my imports:

import * as THREE from 'three';
import { PerspectiveCamera } from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js'
let loader = new GLTFLoader();
loader.load( './js/assets/brain.gltf', function ( gltf )
{
  brain = gltf.scene;
  brain.scale.set(2, 2, 2);
  brain.position.y = 4;
  scene.add(brain);
} );  

HTML:

  <script async src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="096c7a2464666d7c656c247a6160647a4938273a273f">[email protected]</a>/dist/es-module-shims.js"></script>
  <script type="importmap">
    {
      "imports": {
        "three": "../build/three.module.js",
        "three/addons/": "./jsm/"
      }
    }
  </script>
  <script type="module" src="./js/index.js" defer></script>
</body>

Are my asset paths correct? Take a look at my path.

I have experimented with various GLTF files, tested using GLB files, and even made changes to my file paths, but unfortunately, I keep encountering the same error.

Answer №1

I encountered a similar issue: the root cause was an incorrect file path.

Avoid using relative paths.

To resolve this, place the glb file in your public directory and only specify the glb filename when utilizing GLTFLoader.

For instance:

loader.load('a.glb', (obj) => {})

Answer №2

It was frustrating to encounter the same issue with an Unexpected token '<', "<!DOCTYPE "... which is not valid JSON

Fortunately, I resolved it by adding the .glb folder to the public folder in my React project.

npx GLTFjsx <name.glb>

This allowed me to create a React component and load the model using the useGLTF hook from @react-three/drei.

I'm hopeful that this solution will be helpful to others facing a similar problem.

Many thanks.

Answer №3

The issue at hand is the failure to recognize the file path. The problem arises when attempting to include a relative file path that is not recognized because the gltf file must be within the public folder of the framework.

For example: (Incorrect Method)

    const loader = new GLTFLoader();
loader.load('Project/public/sample.gltf', function (gltf) {
    scene.add(gltf.scene);
});

(Correct Method)

    const loader = new GLTFLoader();
loader.load('/sample.gltf', function (gltf) {
    scene.add(gltf.scene);
});

Answer №4

If you haven't figured it out yet, here's what worked for me.

Make sure to have forest.glb saved in the public/data folder.

Using GLTFLoader, load the 3D model with the path 'data/forest_3d_model.glb'. If there is an error, handle it appropriately.

Remember, without the initial "/", the path is directed to the public folder and everything is referenced from there.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring ways to programmatically include questions in the meta.js file of a Vue Webpack template

I have made a customized version of the Vue Webpack template and am currently modifying the meta.js file. I am attempting to figure out how to include a new property in prompts as shown below: "pages": { "type": "input", "required": true, ...

Having trouble with shipit.js deployment: Error encountered - git checkout undefined

I have been using shipit.js to deploy my nodejs application on an Ubuntu 16.04 server successfully. However, I recently encountered the following error: ./node_modules/shipit-cli/bin/shipit production deploy start Running 'deploy:init' task... ...

Preventing Div items from rearranging during size transitions using toggleClass

When I click on an element with the ID "id", I use toggleClass to resize a div from 10px to 500px in width. This is done partly to show/hide content. However, the issue arises when the transition occurs and the contents of the div start rearranging, overfl ...

Combining Express and React for seamless email sending functionality

Attempting to merge a React.js form with a backend setup using Express to send emails. Uncertain of the proper way to format the form body or which HTTP request method to utilize. React.js and Express.js are located in separate directories. express-mailer ...

using Javascript to calculate motion based on specified angle

http://pastebin.com/3vwiTUyT I have posted my code here and need assistance. Specifically, I am trying to make krog1 move within the canvas based on a specific angle that I set. Unfortunately, I am unsure how to accomplish this task. ...

What is the best way to initiate a page refresh from a separate component in ReactJS?

As a newcomer to React, I am facing an issue in my CRUD application. I have a Main component and in the List Component, I need to fetch data from the server using an API call. The problem arises when I submit a new item in the Create component - I have to ...

Modifying element information in JavaScript for a Django/Heroku web application

Is it possible for me to update the values of a data object within my JavaScript code? My JavaScript receives post messages from an iframe, and I need to store this information in the correct objects. However, I am unsure if this can be done on the HTML su ...

Verifying the similarity of usernames using a JSON array

My attempts to create a function that verifies if app.account_username matches a username in a json array are just leading me in circles. This is how the json array is structured { "data": { "id": 32607158, "with_account": "user1", "with_account_id": 84 ...

What steps should I take to export a function from a React functional component in order to create a reusable library?

Currently, I am in the midst of developing a React component library and one of my components contains a function that I want to export. The purpose of the addParticle function is to enable users of the library to dynamically insert particles into a cont ...

Load a query in Codeigniter when the page is first accessed

Can someone provide guidance on calling a query when the page loads or is ready in CodeIgniter? I am unsure of how to execute a query using AJAX or JavaScript. For example, calling an update query. Thank you. ...

How do I make a component in React delete itself from a page when its internal state changes?

For instance: {!loading ? (data.map((v, i) => { return <Card key={i} title={v.name} image={v.pictures.sizes[4].link}} /> }) These cards are displayed as a series of components on the main screen. Each card ...

Node.js: Extracting parameters from the URL

When working with Rails, I make a POST request to my server: response = Typhoeus::Request.post("http://url.localtunnel.com/request?from=ola&to=ole") result = JSON.parse(response.body) Now in my Node.js application, I need to retrieve values for From ...

When using Node.js, Express.js, and MongoDB, ensure that the route.post() function is provided with proper callback functions instead of

I've been working on setting up a MEAN (MongoDB, Express, Node.js, Angular 6) application. I'm trying to post user signup form data to a MongoDB database, but I keep getting an error message. This is my first time working with the MEAN stack and ...

Leveraging the back button in an AngularJS Mobile SPA

Utilizing AngularJS for my Single Page App (SPA), I am currently exploring the most effective way to handle the back button functionality on mobile devices. My setup involves a single JavaScript file, one HTML page, and no partials. The content is reveale ...

Tips for implementing validation in JavaScript

I'm brand new to learning Javascript. Recently, I created a template for a login page and it's working perfectly fine. However, I am struggling with setting up validation and navigation. My goal is to redirect the user to another page if their us ...

What are the steps to testing an endpoint with Jasmine/Karma?

Within one of my components, there is a method that makes a call to an endpoint in the following manner... private async getRolesAsync(): Promise<void> { const roles = await this.http.get<any>('https://sample-endpoint.com').toProm ...

What is the best way to access POST request data in a Node JS controller?

Journey on the Path (routes/account.js) const express = require('express'); const router = express(); var account_controller = require('../controllers/accountController'); router.post('/account/Getuser', account_controller. ...

Issue encountered while attempting to send a POST request from a React application to the Rocket backend

When attempting to send a POST request from my single page application, I encounter a 404 error, even though the route functions properly in Postman. routes.rs #[post("/letters", format = "application/json", data = "<new_letter>")] fn write_letter( ...

Tips on extracting JSON subcategories?

I am currently attempting to retrieve information from a local JSON file using the following JavaScript script: let accordion=document.querySelector('#accordion'); fetch('countries.json') .then(function(response){ return response.js ...

Can you explain the significance of this HTML code?

While examining some source code, I came across the following: <div class="classname {height: 300px; width: 200px}"></div> I am aware that element styling can be done using the style="" attribute. Could you explain what this code snippet sig ...