简体   繁体   中英

How to send data received from external graphql api with nodejs to frontend (reactjs)

This graphql api I found on the internet is showing cors error when I call it with fetch or apollo client from frontend, So I searched for a solution and I found out that if I call api from server, cors error will go away so I followed a basic tutorial about express and set up one, then call graphql api in my server/index.js

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

Now I get the data back in my terminal but I don't know how to send those data back to my frontend which is in frontend/App.js to show data on my page. Can someone help me with this? I am quite new to express and graphql so I might be doing it all wrong. Thanks

The idea is something like this:

  1. Frontend makes a request to the backend application.
  2. Backend fetches the data from the GraphQL API and returns it to the client.

So on your express app just build a route

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);
``

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM