【问题标题】:How do I make server-side fetch calls?如何进行服务器端 fetch 调用?
【发布时间】:2021-10-31 04:11:14
【问题描述】:

我有一个 React Web 应用程序,它当前确实在客户端获取调用以使用实时信息(例如当前天气)更新仪表板,这意味着随着用户的增加,它将导致不必要的流量调用,并且可能可能会导致此天气网站崩溃。

我想了解的是如何使这些 fetch 调用成为服务器端的?我已经研究过创建一个 Node.js Express 服务器,但我不确定它是否具有对远程主机进行 fetch 调用的功能。

不幸的是,这是我的请求天气代码,但它并没有真正起作用。

const { response } = require('express');
const express = require('express'); 
const app = express(); 
var fetch = require('node-fetch');
const port = process.env.PORT || 5000; 

app.use(express.json());

// This displays message that the server running and listening to specified port
app.listen(port, () => console.log(`Listening on port ${port}`)); 

// create a GET route
app.get('/request-info', (req, res) => { 

  res.send({ information: 'information call successful' });

});

app.get('/request-weather', (req, res) => {
    fetch('http://thisotherwebsite.com/weather-query-that-returns-json',
        {method: 'GET',
        headers: {' Accept': 'application/json'}})
        .then(res => {
            return res;
        })
    });

【问题讨论】:

    标签: node.js reactjs backend react-fullstack


    【解决方案1】:

    几件事:

    1. 您的/request-weather 处理程序向thisotherwebsite 发出请求,但没有对响应做任何事情。

    2. 您的.then(res => { return res; }) 实际上并没有做任何事情。您只是获取 fetch 已经返回的内容并将其返回。

    如果您想将响应发送回浏览器,您可以执行以下操作:

    fetch(...) // make the request
      .then(result => result.json()) // extract the data
      .then(data => {
        res.json(data); // send it to the browser
      })
    

    如果你想进行额外的处理,你可以await fetch 调用,然后做任何你需要做的事情:

    app.get('/request-weather', async (req, res) => { // make handler async
    
      // get data from the other site
      const data = await fetch(...)
        .then(response => response.json());
      
      // package it up with some other stuff
      responseData = {
        fromOtherSite: data,
        myExpressStuff: {
          foo: 1,
          bar: 2,
        }
      }
    
      // return it to the browser
      res.json(responseData);
    

    参考:

    【讨论】:

    • 我收到[ERR_REQUIRE_ESM]: Must use import to load ES Module 错误,指向我需要节点提取的第 4 行。知道如何解决这个问题吗?
    • 如消息所述,您需要使用import 进行节点获取,而不是requirethe documentation中有例子。
    猜你喜欢
    • 1970-01-01
    • 2021-05-16
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 2016-01-21
    • 1970-01-01
    相关资源
    最近更新 更多