As a newcomer to JavaScript, I recently came across a text document filled with nouns and thought it would be a great idea to create an API using these words.
I parsed the file and stored the nouns in a List:
public List<Noun> getData() throws IOException {
Scanner sc = new Scanner(new
File("C:\\Users\\Admin\\Desktop\\nounlist.txt"));
List<Noun> nouns = new ArrayList();
while (sc.hasNextLine()) {
nouns.add(new Noun(sc.nextLine()));
}
return nouns;
}
I then converted this list to Json using Gson:
@GET
@Path("/nouns/amount=all")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response getAllNouns() throws IOException {
return Response.ok().entity(gson.toJson(nf.getData())).build();
}
Next, I started working on the frontend using JS and attempted to fetch the data. However, I encountered an error stating "uncaught in promise, type error, nouns.forEach is not a function."
import "bootstrap/dist/css/bootstrap.css";
const root = document.getElementById("root");
var url = "http://localhost:8084/CORSJavaJax-rs/api/noun/nouns/amount=all";
var tbody = document.getElementById("tbody");
var btn = document.getElementById("btnsend");
// fetch(url)
// .then(res => res.json)
// .then(nouns => {
// var n = nouns.map(noun => {
// return "<tr>" + "<td>" + noun.name + "</td>" + "</tr>";
// });
// tbody.innerHTML = n.join("");
// });
btn.addEventListener("click", function() {
fetch(url)
.then(res => res.json)
.then(nouns => {
console.log(nouns);
var n = nouns.forEach(noun => {
return "<tr>" + "<td>" + noun.name + "</td>" + "</tr>";
});
tbody.innerHTML = n.join("");
});
});
I have tried using both map and forEach methods without success. It seems like there might be something missing or a misunderstanding on my part regarding why I am unable to map the data.