Mike
Mike

Reputation: 23

Javascript fetch API doesnt work when used in EJS file

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"
    }
]
}

Upvotes: 0

Views: 792

Answers (2)

Ghost
Ghost

Reputation: 5049

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));

Upvotes: 1

Barrios
Barrios

Reputation: 65

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)

Upvotes: 1

Related Questions