请求拥有API终结点

Request to own API endpoint

本文关键字:结点 API 拥有 请求      更新时间:2023-09-26

在node/express端,我正试图向刚刚创建的端点发出get请求。

正确的方法是什么?我可以使用提取库(同构提取)吗

我的尝试:

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
  })