【问题标题】:How to send data received from external graphql api with nodejs to frontend (reactjs)如何使用nodejs将从外部graphql api接收到的数据发送到前端(reactjs)
【发布时间】:2021-06-14 18:31:39
【问题描述】:

我在互联网上找到的这个graphql api在我从前端使用fetch或apollo客户端调用它时显示cors错误,所以我搜索了一个解决方案,我发现如果我从服务器调用api,cors错误就会消失所以我按照关于 express 的基本教程进行了设置,然后在我的server/index.js中调用 graphql api

const express = require("express");
const rp = require("request-promise");
rp("https://.../graphql", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    query: `
          query {
              heroSearchByName(name: "John") {
                name
              }
          }
          `,
  }),
})
  .then((body) => {
    console.log(body); // result
  })
  .catch((err) => {
    console.log(err);
  });

const PORT = 4000;
const app = express();
console.log(`Server listening on http://localhost:${PORT} ...`);
app.listen(PORT);

现在我在终端中取回数据,但我不知道如何将这些数据发送回位于frontend/App.js 的前端以在我的页面上显示数据。有人可以帮我弄这个吗 ?我对表达和graphql很陌生,所以我可能做错了。谢谢

【问题讨论】:

  • 在您的 graphql 服务器解析器中使用它,将接收到的数据调整为所需的形状(解析器返回类型)
  • 你能用更初学者的方式解释一下吗?以下答案有效,但我认为应该有更好和更先进的方法来实现它。我还将阅读 graphql 解析器,谢谢。
  • 这是关于自己的 graphql 服务器(apollo),其中一些查询转发到外部 graphql 服务器......可能github.com/chimurai/http-proxy-middleware 会更简单

标签: node.js reactjs graphql


【解决方案1】:

这个想法是这样的:

  1. 前端向后端应用发出请求。
  2. 后端从 GraphQL API 获取数据并将其返回给客户端。

所以在你的快递应用上建立一条路线

const express = require("express");
const rp = require("request-promise");

app.post('/fetchData', function (req, res) {
rp("https://.../graphql", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    query: `
          query {
              heroSearchByName(name: "John") {
                name
              }
          }
          `,
  }),
})
  .then((body) => {
    res.send(body)
  })
  .catch((err) => {
    console.log(err);
  });


})

const PORT = 4000;
const app = express();
console.log(`Server listening on http://localhost:${PORT} ...`);
app.listen(PORT);
``

【讨论】:

  • 更有可能他仍然想使用 graphql 客户端 [在 FE 上] 并且只将“代理”/转发请求到另一台服务器......转发原始查询(来自请求正文)并使用会很好/graphql发布路线
  • 非常感谢。
猜你喜欢
  • 2020-08-31
  • 2020-11-23
  • 1970-01-01
  • 1970-01-01
  • 2019-05-14
  • 1970-01-01
  • 2021-09-11
  • 1970-01-01
  • 2021-11-28
相关资源
最近更新 更多