【问题标题】:Sending data to Nodejs backend in Reactjs for API call在 Reactjs 中将数据发送到 Nodejs 后端以进行 API 调用
【发布时间】:2021-06-02 19:22:00
【问题描述】:

我正在尝试从 Reactjs 将数据发送到我的 Nodejs 服务器(托管在 Firebase 上),以从 API 调用中检索数据。

当 API url 被硬编码时它可以工作,所以问题应该是从 React 向 Node.js 发送数据。我目前正试图让它只返回一个请求,但一旦我能够做到这一点,我将尝试获取多个请求。

结果是用响应填充股票状态。

我的 React 代码如下所示:

class Table extends Component {
  constructor (props)
  {
     super(props);
      this.state = {
         favorites: ['APPL'],
         stocks: []
     };
 }

   componentDidMount() {
   // http is adjusted for stackoverflow
    fetch('http://localhost:5001/', { 
      // new part:
      method: 'post',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
        favorites: this.state.favorites})
      // old part - worked before i tried to send data to the backend:
    })
    .then((response) => response.json())
    .then(stockList => {
        this.setState({ stocks: stockList });
            console.log(stockList);
    });
}

节点代码:

const functions = require("firebase-functions");
const express = require("express");
const fetch = require("node-fetch");
const cors = require("cors");

    const app = express();
    app.use(cors({origin: true}));
    
    app.get('/', async (request, response) => {
      // new line that was ment to catch the data from frontend.
      const favorites = request.body.favorites
      // web and key is the rest of the API call.
      const url = web+favorites+key;
      const fetchResponse = await fetch(url);
      const symbol = await fetchResponse.json();
      response.json(symbol);
    });

【问题讨论】:

  • 你说它以前用硬编码的 URL 工作,现在不能工作吗?如果没有,您遇到什么错误或什么不起作用?我还注意到您在 React 代码中发送 POST 请求,但您在 Node 代码中的路由是针对 GET 请求(app.get 而不是 app.post),对吗?
  • 嗨@ÁlvaroZamora,问题似乎是我没有将数据从反应发送到节点,这导致了这个错误:UnhandledPromiseRejectionWarning: FetchError: invalid json response body at sandbox.iexapis.com/stable/stock/undefined/quote?token=。我已经删除了令牌,但是如果您在中间看到未定义的,那应该是“aapl”(在发布的代码中是错误的,但我已经更正了。)我正在使用一个帖子来响应发送数据到节点并编辑发送到 iexcloud 的 url,但我不知道这是否是这样做的方法。
  • 哦,我想我明白你在做什么了。 React 通过 POST 请求将数据发送到 Node,Node 向您刚刚链接的 API 发出 GET 请求以获取信息。在这种情况下,您将在 Node 代码中缺少一个 POST 端点来获取数据,不是吗?我相信您将两个不同的请求合二为一。
  • @ÁlvaroZamora 是的。 TBH,我不知道我做错了什么。你知道如何解决它吗?我不确定如何在节点代码中添加 POST 端点。
  • @ÁlvaroZamora like so?: app.post('/', (request, response) => { // 这是从正文获取 POST 数据的方法 const favorites = console.log( req.body.favorites) // 此处通过 GET 请求将 POST 请求中的数据发送到 API app.get('/', async (request, response) => { // const favorites = request.body.favorites ; // console.log(favorites) const url = web+favorites+key; const fetchResponse = await fetch(url); const symbol = await fetchResponse.json(); response.json(symbol); }); })

标签: node.js reactjs https google-cloud-functions


【解决方案1】:

为了从前端获取数据,您需要在 Node 服务器中创建一个 post 端点,并在该方法中发送一个 GET 请求。

const functions = require("firebase-functions");
const express = require("express");
const fetch = require("node-fetch");
const cors = require("cors");

    const app = express();
    app.use(cors({origin: true}));
    
    app.post('/', (req, res) => {
        // here is how you get the POST data from the body
        console.log(req.body.favorites)
        
        // send the data from the POST request to the API through a GET request here

    })

现在您需要在我放置评论的地方发出 GET 请求,您可以使用更简单的 https node.js library 来实现。

【讨论】:

    【解决方案2】:

    在我的问题中,我正在尝试使用 Firebase 函数来处理指向外部 API 的链接,并在我的前端使用来自该 API 的数据。

    在 Stackoverflow 的帮助下,我发现这可能不是一个理想的方法。我基本上是想在前端和 API 之间添加一个层,但这不是必需的,因为可以直接在 React 中访问 API。这将从 Firebase 中移除该功能,这意味着更少的步骤、更少的代码和更少的费用。

    因此,对于 state.favorites 中的每个实例,相关数据都会从 API 中提取并存储在 state.stocks 中。

    这段代码成功了:

    class Table extends Component {
      constructor (props)
      {
         super(props);
          this.state = {
             favorites: ['aapl', 'arvl'],
             stocks: []
         };
     }
    
          componentDidMount() {
            this.state.favorites.map((favorites, index) => {
            fetch(`API_website${favorites}/(API_token`)
                .then((response) => response.json())
                .then(stockList => {
                   this.setState({ stocks: stockList });
                       console.log(stockList);
               });
            })
          }
    

    【讨论】:

      猜你喜欢
      • 2020-08-31
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 2019-05-14
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      相关资源
      最近更新 更多