猿问

未兑现承诺

所以我对 JavaScript 还很陌生,我有一个充满名词的文本文档,并认为用这些名词创建 api 的好方法。


我阅读了文件并将它们添加到列表中


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;

}

这个列表我用 Gson 转换为 Json:


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

}

然后我开始用 js 创建我的前端并尝试获取数据,但遇到了一个问题,说 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("");

    });

});

我尝试了 map 和 forEach 但没有成功,也许我错过了一些东西,或者有些东西我只是不明白为什么我不能映射数据。



温温酱
浏览 114回答 1
1回答

胡说叔叔

对于您想要的,正确的用法是map调用,而不是forEach. ForEach 不返回值,它只是在集合上迭代。您收到is not a function错误的原因很可能是由于缺少对res.json. 应该是res.json()。btn.addEventListener("click", function() {&nbsp; fetch(url)&nbsp; &nbsp; .then(res => res.json())&nbsp; &nbsp; .then(nouns => {&nbsp; &nbsp; &nbsp; console.log(nouns);&nbsp; &nbsp; &nbsp; var n = nouns.map(noun => {&nbsp; &nbsp; &nbsp; &nbsp; return "<tr>" + "<td>" + noun.name + "</td>" + "</tr>";&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; tbody.innerHTML = n.join("");&nbsp; &nbsp; });});
随时随地看视频慕课网APP

相关分类

Java
我要回答