【问题标题】:How to view json data sent from express using javascript?如何使用javascript查看从express发送的json数据?
【发布时间】:2020-12-08 02:51:48
【问题描述】:

使用节点,我有一个 client-server model ,客户端将在其中连接到“localhost”,并且 express 将根据逻辑提供一个 response。我了解如何通过 response 发送 json 对象,但我不知道如何在我的客户端脚本中访问此 json 对象。新手有什么想法吗?

服务器:

app.get("/", function(request,response){
 response.json({ username: 'example' })
 
 })

【问题讨论】:

  • 您的客户端 javascript 可以向路由“/”发出 GET 请求。您可以使用许多技术来发出此请求,例如使用fetch() API、XMLHttpRequest、jQuery 的 $.ajax、angular 的 HttpClient 模块、axios 等……如果您在客户端使用 vanilla JS,那么fetch() 可能是最简单的选择。
  • fetch 是否作为第二个获取请求?或者它只是提供从初始获取请求中存储的数据
  • 它将作为第二个 GET 请求。当您在浏览器中输入 localhost(即:一个 URL)时,您的浏览器会为您发出 GET 请求,然后您的服务器可以响应页面内容,例如您刚刚请求的页面的 HTML、CSS、JS 等。然后,稍后,您的 JS 代码可以向您的服务器发出第二次(或第三次或第四次等)请求以获取特定路由,该路由通常会以 JSON 响应(如您的示例中所示)

标签: javascript express http


【解决方案1】:

如果你使用 Vanilla JS,你有一些选择,例如 Fetch API、XMLHttpRequest、ajax。

1.获取 API:

fetch('http://localhost:3000/')
    .then(response => console.log(response));

2。 XMLHttpRequest :

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       console.log(xhttp.responseText);
    }
};
xhttp.open("GET", "http://localhost:3000/", true);
xhttp.send();

3.阿贾克斯:

$.get("http://localhost:3000/", function(data, status){
    console.log(data);
  });

您可以将"http://localhost:3000/" 替换为您的网址。

【讨论】:

  • 可能值得展示如何从响应对象中提取数据 (.then(response => response.json()).then(data => console.log(data));)
  • $.get 这将需要 jQuery
猜你喜欢
  • 2015-12-30
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
  • 1970-01-01
  • 1970-01-01
  • 2017-10-28
  • 1970-01-01
  • 2017-06-10
相关资源
最近更新 更多