【问题标题】:Send data between GraphQL Node.js server and React in Nx在 GraphQL Node.js 服务器和 Nx 中的 React 之间发送数据
【发布时间】:2021-11-19 23:31:02
【问题描述】:

我在Nxmonorepo 中设置了两个项目,Node.js 和 React。我想使用 GraphQL 进行通信。我使用命令 nx serve api(Node.js) 和 nx serve totodile (React) 运行的项目。问题是 React 无法从 /graphql 端点访问数据。

React 正在 http://localhost:4200/ 上运行。
Node.js 在http://localhost:3333/ 上运行。

Node.js 部分

根据GraphQL instructions for Node.js 我运行Node.js 服务器。我创建了两个端点/api/graphql

import * as express from 'express';
import { graphqlHTTP } from 'express-graphql';
import { Message } from '@totodile/api-interfaces';
import { buildSchema } from 'graphql';

const app = express();

const greeting: Message = { message: 'Welcome to api!' };

app.get('/api', (req, res) => {
  res.send(greeting);
});

app.use('/graphql', graphqlHTTP({
  schema: buildSchema(`
  type Query {
    hello : String
  }
`),
  rootValue: {
    hello: () => 'Hello world'
  },
  graphiql: true,
}));

const port = process.env.port || 3333;
const server = app.listen(port, () => {
  console.log('Listening at http://localhost:' + port + '/api');
});
server.on('error', console.error);

结果我能够连接到http://localhost:3333/graphql 并接收响应。所以graphql服务器运行良好。

// graphql response
{
  "data": {
    "hello": "Hello world"
  }
}

反应部分

我使用/api/graphql 获取的内部功能组件。第一个返回有效数据,但 /graphql 返回 404无法 POST /graphql

  useEffect(() => {
    fetch('/api') // successfully return data
      .then((r) => r.json())
      .then(setMessage);  

    fetch('/graphql', { // 404, no data
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
      body: JSON.stringify({query: "{ hello }"})
    })
      .then(r => r.json())
      .then(data => console.log('data returned:', data)); 
  }, []);

我对此进行了调查:

http://localhost:4200/api return valid data ("message": "Welcome to api!")
http://localhost:3333/api return valid data ("message": "Welcome to api!")

http://localhost:4200/graphql 404 no data
http://localhost:3333/graphql return valid data ("hello": "Hello world")

一定是有端口的东西。
我不明白/api 是如何返回任何数据的。为什么在两个端口上?
我应该怎么做才能共享来自/graphql 的数据以做出反应?

【问题讨论】:

  • 比较网络请求,至少使用完整的url和端口
  • 使用http://localhost:3333/graphql 获取会导致“405 方法不允许”。
  • “比较网络请求”的原因 - 调整您的代码以与工作代码相同(graphiql/playground)

标签: javascript node.js reactjs graphql nx.dev


【解决方案1】:

要解决问题,需要执行 2 个步骤:

  1. 在 React 中,我应该使用端口 fetch('http://localhost:3333/graphql',(...)) 从端点获取
  2. 在Node.js中需要使用cors
import express from "express";
import cors from 'cors';

const app = express();

app.use(cors());

app.use('/graphql', graphqlHTTP({
 schema: schema,
 rootValue: root,
 graphiql: true,
}));

...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 2022-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多