When I try to Fetch GET data from an API, I get the following error on index.html page when loading-
script.js:14 SyntaxError: Unexpected end of input
at script.js:10
(anonymous) @ script.js:14
Promise.catch (async)
foodApi @ script.js:14
(anonymous) @ script.js:18
Here is the JSON I'm trying to fetch from URL (http://localhost:3000/food/). If I go to that URL I'm able to see the JSON I created.
[{"calories":140,"_id":"5f47f19289fb9913fd136a7a","name":"small potato","__v":0},{"calories":120,"_id":"5f4801ab674e691ec6350d64","name":"sweet potato","__v":0},{"calories":234,"_id":"5f48236092d55f1c226936b0","name":"avocado","__v":0}]
This is the client side javascript code I'm using to get the data, but instead get the above error on index.html
Does anybody know a solution?
this is the client side javascript code (script.js):
const textAPI = document.querySelector("#textAPI");
const url = "http://localhost:3000/food/";
function foodApi() {
fetch(url, {
method: "GET",
mode: "no-cors",
})
.then((response) => response.json())
.then((data) => {
textAPI.innerHTML = "from the db: " + JSON.stringify(data);
})
.catch((error) => console.error(error));
}
foodApi();
this is the server side API (foodRoutes.js):
const express = require("express");
const foodModel = require("../models/food");
const fetch = require("node-fetch").default;
const app = express();
//get all
app.get("/food", async (req, res) => {
const food = await foodModel.find({});
try {
res.type("json").send(food);
} catch (error) {
res.status(500).send(error);
}
});
module.exports = app;
this is the html (index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>atlas test</title>
</head>
<body>
<div class="textAPI">
<p id="textAPI">initial start</p>
</div>
</body>
<script src="script.js"></script>
</html>