如何在javascript文件中使用我的本地API?

如何在javascript文件中使用我的本地API?,javascript,node.js,express,mongoose,Javascript,Node.js,Express,Mongoose,我有一个文件api.js,其中包含以下内容: exports.showAll = function(req, res) { Obj.find(function(err, Objs) { res.send(Objs); }); } 我的服务器有以下行: app.get('/all', api.showAll); 当我在浏览器中加载/all时,我得到了JSON,但我想把这个JSON放到客户端JS文件中,这样我就可以在网页上漂亮地显示JSON数据 如何在客户端JS文

我有一个文件
api.js
,其中包含以下内容:

exports.showAll = function(req, res) {
    Obj.find(function(err, Objs) {
        res.send(Objs);
    });
}
我的服务器有以下行:

app.get('/all', api.showAll);
当我在浏览器中加载
/all
时,我得到了JSON,但我想把这个JSON放到客户端JS文件中,这样我就可以在网页上漂亮地显示JSON数据


如何在客户端JS文件中使用服务器端API?

要调用服务器并处理结果,需要使用。AJAX代表异步JavaScript和XML,但实际情况是,您可以通过其他语言进行此类调用,而无需检索XML。以下是如何向服务器发出请求的简单示例:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  // Verify that the request is done and completed successfully
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      var json = xhr.responseText;
      var data = JSON.parse(json); // Parse the JSON into an actual object/array
      console.log(data);
    } else {
      console.log('Something went wrong');
    }
  }
};
xhr.open('GET', '/all');
xhr.send();

要调用服务器并处理结果,需要使用。AJAX代表异步JavaScript和XML,但实际情况是,您可以通过其他语言进行此类调用,而无需检索XML。以下是如何向服务器发出请求的简单示例:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  // Verify that the request is done and completed successfully
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      var json = xhr.responseText;
      var data = JSON.parse(json); // Parse the JSON into an actual object/array
      console.log(data);
    } else {
      console.log('Something went wrong');
    }
  }
};
xhr.open('GET', '/all');
xhr.send();
你要找的是。这将允许您从客户端脚本向服务器发出请求,并根据需要处理该请求的结果。这将允许您从客户端脚本向服务器发出请求,并根据需要处理该请求的结果。