这是我的应用程序的工作方式:我从API获取推文,并将其本地写入Apollo服务器中的json文件中。然后,我想使用GraphQL从Apollo服务器获取这些推文。可悲的是,似乎无法链接fetch
和refetch
(来自Apollo GraphQL查询)。当我运行下面的代码时,总是会收到错误Failed to load resource: Could not connect to the server.
(错误发生后刷新时,数据是正确的)。但是,如果在我的表单中,我仅请求第一个API,请等待几秒钟,然后按类似<button onClick={() => refetch()}>Refetch!</button>
的按钮,即可使用。
代码如下:
let data = <Query
query={gql`
{
twitQueries {
id
text
username
retweets
likes
}
}
`}
>
{ ({ loading, error, data, refetch }) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error</p>;
const tweets = <div> my tweets </div>;
return <div id='formAndTweets'>
<button onClick={() => refetch()}>Refetch!</button>
<form onSubmit={(e) => {
e.preventDefault();
const username = this.state.username;
const controller = new AbortController();
const signal = controller.signal
fetch('http://localhost:5000/user/'+username+'/max/10', {
method: 'GET', signal: signal
}).then((res) => {
return res.json().then((data) => {
this.setState({request: 'done'});
return refetch();
});
});
}}>
<label htmlFor="username">Username: </label>
<input id="username" name="username" type="text" value={this.state.username} onChange={(e) => { this.setState({username: e.target.value}); }}/>
<input type="submit" value="Search" />
</form>
{tweets}
</div>
}}
</Query>
为什么我不能做fetch(...).then(() => { refetch() })
之类的事情,而又不用等待另一个按钮就可以解决该问题?
更新:它与公共Apollo服务器一起使用。所以这一定是我的事,但我找不到。这是代码:
index.js:
import express from 'express';
import bodyParser from 'body-parser';
import { graphqlExpress, graphiqlExpress } from 'apollo-server-express';
import { makeExecutableSchema } from 'graphql-tools';
import path from 'path'
import fs from 'fs'
import cors from 'cors'
import resolvers from './resolvers'
const typeDefs = fs.readFileSync(path.join(__dirname, 'model.graphql'),{encoding:'utf-8'})
const myGraphQLSchema = makeExecutableSchema({typeDefs, resolvers})
const PORT = 4000;
const app = express();
app.use(cors()); // enable `cors` to set HTTP response header: Access-Control-Allow-Origin: *
// bodyParser is needed just for POST.
app.use('/graphql', bodyParser.json(), graphqlExpress({
schema: myGraphQLSchema,
}));
app.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
}),
);
app.listen(PORT);
resolver.js:
var exec = require('child-process-promise').exec;
const util = require('util');
const fs = require('fs');
const readFile = util.promisify(fs.readFile)
//updated by the first API
const testJsonPath = 'tweets.json';
const resolvers = {
MyQueryType: {
twitQueries(root,args,context) {
return readFile(testJsonPath).then(content =>{
return JSON.parse(content);
})
}
}
}
export default resolvers;
model.graphql
scalar Date
type TweeterQuery{
id: String
username: String
}
type Twit{
id: ID!
username: String!
date: String!
replies: Int!
retweets: Int!
likes: Int!
geo: String
mentions: String
hashtags: String
permalink: String!
emoticons: Int!
emoticonsStr: String
replying: Int!
replyingTo: String
text: String!
}
type Member{
id: ID!
login: String
}
type MyQueryType{
twitQueries(id: ID):[Twit]
}
schema{
query: MyQueryType
#mutation: Mutation
#subscription: Subscription
}
input TwitInput{
author:AuthorInput
}
input AuthorInput{
id:ID
login:String
}
这真的让我感到奇怪,因为正如我所说的,它在第一个fetch
之后等待几秒钟时才真正起作用。我只是不知道问题出在我的服务器上。