javascript - 请求自己的 API 端点

标签 javascript node.js rest express

在 Node/express 端,我尝试向我刚刚创建的端点发出 get 请求。

正确的做法是什么?我可以使用 fetch 库(isomorphic-fetch)

我的尝试:

router.get('/displayweather', function(req, res) {  

  fetch('/weather')
    .then(function(response){
      res.send(response);
    });
});

router.get('/weather', function(req, res){
  var fetchUrl = 'http://api.wunderground.com/api/xyz-token/conditions/q/CA/San_Francisco.json';
  fetch(fetchUrl)
    .then(function(response){
      if (response.status >= 400) {
        throw new Error("Bad request response from server");
      }
      return response.text();

    }).then(function(body) {
      res.send(body);

    });

});

还有另一个 router.get(..) 方法使用外部 API 检索天气数据

最佳答案

我会忘记第一部分并专注于您添加的代码:

服务器

router.get('/weather', function(req, res){
  var fetchUrl = 'http://api.wunderground.com/api/xyz-token/conditions/q/CA/San_Francisco.json';
  fetch(fetchUrl)
    .then(function(response){
      if (response.status >= 400) {
        throw new Error("Bad request response from server");
      }

      // return json
      return response.json();
    }).then(function(body) {

      // but stringify it when you send it
      res.send(JSON.stringify(body));
    });
});

客户端

fetch('/weather')
  .then(function (json) {
    return JSON.parse(json);
  })
  .then(function (data) {
    // do something with the data
  })

关于javascript - 请求自己的 API 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37003865/

相关文章:

javascript - 有没有办法在 SetState 中使用 async wait

javascript - 导航切换脚本与页面特定脚本不兼容

Javascript 原型(prototype)方法 "Cannot set property"

node.js - 使用 unirest 库、Node.js 下载文件

rest - 如何使用 HttpClient 类请求多个 URL 而不会丢失 URL 之间的关系

Perl REST 客户端,身份验证问题

javascript - 从外部 js 文件访问函数时 Onblur 不起作用

javascript - 启动时 Node 检查器错误

node.js - 使用 restify 提供静态文件

java - Spring MVC 中 REST 响应对象的部分 JSON 序列化