-1

我在Nx monorepo中设置了两个项目,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 部分

根据 Node.js 的GraphQL 指令,我运行 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"
  }
}

反应部分

在功能组件内部,我使用/apiand获取/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以做出反应?

4

1 回答 1

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

...
于 2021-09-30T11:38:41.293 回答