0

I have a webpage that fetches information about products from a JSON file in my computer. The problem is that when .json() gets executed, I get the error SyntaxError: Unexpected end of input. This only happens if I run the webpage directly in the file system (opening the .html file) while, in the other hand, if I run the webpage in a server It works properly. Someone can tell me why and how to fix this issue?

async function obtener (url) { if (typeof(url) !== 'string') return const respuesta = await fetch(url, { mode: "no-cors", headers: { "Content-Type": "application/json", } }) return respuesta.json() // error is thrown here } const productosURL = './datos/merchandising.json' const productos = await obtener(productosURL) 

JSON file:

[ { "id": "ee154f46-10d4-4007-9ecf-44332bc45346", "nombre": "Camiseta Prematch - 2023", "categoria": "Hombre Fútbol", "precio": 11000, "disponible": true, "imgURL": "./recursos/img/productos/futbolprematch2023.jpg" }, { "id": "4d20afcc-516d-4118-8b34-6cd17c17772c", "nombre": "Camiseta Titular - 2023", "categoria": "Hombre Fútbol", "precio": 15000, "disponible": true, "imgURL": "./recursos/img/productos/futbol-titular2023.jpg" }, { "id": "778f7c59-4e9d-45a6-8b2e-2f9cb466476b", "nombre": "Camiseta Alternativa - 2023", "categoria": "Hombre Fútbol", "precio": 9000, "disponible": true, "imgURL": "./recursos/img/productos/futbol-alternativa2023.jpg" } ] 

Project's file structure. I run the webpage by opening merchandising.html (no server running)

structure of this project

7
  • 1
    "This only happens if I run the webpage directly in the file system (opening the .html file)" - I'd expect AJAX operations to fail in that scenario. It sounds like the test itself is invalid in this case. (Surely there's a duplicate I'm just not finding about AJAX requests to/from the file system...) Commented Jul 15, 2023 at 13:03
  • Do you understand mode: "no-cors". JavaScript can't access the body of the response. Commented Jul 15, 2023 at 13:04
  • @David as you commented above, I haven't found a question with this particular scenario (request in the file system). I don't know why this has been closed, related questions don't satisfy this issue, though, I understand the "no-cors" now. Commented Jul 17, 2023 at 18:57
  • @LucasDavidFerrero: What exactly is left to be satisfied for the issue? If you're trying to make an AJAX request to the file system then you can't do that. A file system is not a web server. In the question it sounds like the functionality works as expected when using a web server, so then is that not the solution? Commented Jul 17, 2023 at 18:59
  • 1
    To make it short: You won't find one. It's a security risk and modern browsers won't allow it. Commented Jul 17, 2023 at 20:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.