0

I am trying to fetch a file called files.json from the root directory of the (locally hosted) NodeJS backend and then print it out in the console.

<script>
fetch("./files.json")
    .then(res => {
        return res.json();
    })
    .then(obj => {
        console.log(obj);
    })
    .catch(err => {
        console.error(err);
    });
</script>

Using this code in the index.ejs file delivers the following error in the browser's console:

GET http://localhost:3000/files.json [HTTP/1.1 404 Not Found 2ms]
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

However, when I use the exact same code in an .html file that's hosted locally with Visual Studio Code's LiveServer plugin, I get the desired result:

Object { files: (3) […] }

If it's relevant, files.json has the following content:

{
"files": [
    {
        "name": "testfile1"
    },
    {
        "name": "testfile2"
    },
    {
        "name": "testfile3"
    }
]
}

2 Answers 2

1

You need to convert your data output into string i.e.,

 var yourDataStr = JSON.stringify(yourdata) 

and then validate your data with:

JSON.parse(yourDataStr)

Sign up to request clarification or add additional context in comments.

Comments

1

I am not sure but I think that fetch() won't work with NodeJS. It is only native feature in browsers (Client-side Javascript) So it won't work in NodeJS. To solve this you must download Library in NodeJS that will support fetch() in NodeJS like node-fetch.

  1. Install node-fetch using npm install node-fetch.
  2. Then try this example :
fetch('') // Here add location for JSON file
            .then(res => res.json())
            .then(json => console.log(json));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.