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