javascript - 从运行在node.js上的json获取数据

标签 javascript node.js ajax

我想从 localhost 上的 JSON 对象获取数据。 ..这可能是一个非常愚蠢的问题,但我是 JS 的初学者。

还有其他方式获取数据吗?

  fetch('http://localhost:3000/show')
     .then(result => {
          console.log(result);
          return result.json();
      });
      .then(data => {
         console.log(data);
      });
      .catch(error => {
          console.log(error);
      });

这个http://localhost:3000/show包含 json 对象。 它已从 mongoose 检索数据。

最佳答案

删除每个 .then 调用之间的分号。

Promise 使用一种“monadic”模式:Promise 上的每个方法都会返回另一个 Promise,该 Promise 具有相同的 API。这意味着您可以无限期地链接 Promise 方法。

所以:

fetch()
.then(/* stuff */)
.then(/* more stuff */)
.catch(/* even more stuff */); // <-- this is the only semicolon

许多数组方法也是如此,因此您经常会看到如下代码:

Object.keys( someObj )            // returns an array
.map(/* iterator function */)     // Array.map returns an array
.filter(/* iterator function */)  // Array.filter returns an array
.sort(/* comparator function */); // Array.sort returns an array

同样,只需要一个分号,因为语句的每一步都会生成一个数组,JS 可以让您预见到这一点。

<小时/>

如果这没有帮助,您可能需要发布您遇到的错误。

我应该补充一点,如果 http://localhost:3000/show 上的服务器无法提供 HTTP header Content-Type: application/jsonresult.json() 将抛出异常。即使响应正文是完全有效的 JSON,如果服务器未声明内容是 json,HTTPResponse 类也会拒绝执行 .json()

此外,如果此代码在浏览器中运行,并且从不同的主机(或端口)提供服务,则您将需要执行 CORS 操作。请参阅https://stackoverflow.com/a/48287868/814463寻求可能的帮助。

关于javascript - 从运行在node.js上的json获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53551699/

相关文章:

javascript - 使用 JavaScript 连接字符串有什么问题?

javascript - 主干模型 urlroot

node.js - X-Content-Encoding-Over-Network 位于响应 header 中,但不位于 Content-Encoding 中

AJAX:本地主机上的 "The requested URL was not found on this server"

.net - 从 WCF/ADO.NET 数据服务中的请求正文接收参数

javascript - CKEditor 中的 jQuery UI 可调整大小

javascript - Reactjs - 从数据集构建表单,FormElement 不返回渲染函数

node.js - 使用 kubernetes 部署时无法连接 gRPC

node.js - Node JS Express 样板和渲染

javascript - 将数据从 jQuery.ajax() 传递到 Angular Controller ?