I am using graphql subcriptions for my project, it is an instagram clone and I am doing function to like or unlike post, I use npx create-react-app
to create my client and I use express
to make my server.
at the client side, I set up my client
like that:
src/apis/client.js
import {
ApolloClient,
ApolloLink,
HttpLink,
InMemoryCache,
split,
} from 'apollo-boost';
import {getMainDefinition} from '@apollo/client/utilities';
import {WebSocketLink} from '@apollo/client/link/ws';
const httpUrl = 'http://localhost:5000/graphql';
const wsUrl = 'ws://localhost:5000/graphql';
const httpLink = ApolloLink.from([
new ApolloLink((operation, forward) => {}),
new HttpLink({uri: httpUrl}),
]);
const wsLink = new WebSocketLink({
uri: wsUrl,
options: {
// connectionParams: () => {},
lazy: true,
reconnect: true,
},
});
function isSubscription(operation) {
const definition = getMainDefinition(operation.query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
}
const client = new ApolloClient({
cache: new InMemoryCache(),
link: split(isSubscription, wsLink, httpLink),
defaultOptions: {query: {fetchPolicy: 'no-cache'}},
});
export default client;
As you can see, I use both websocket and https connection. Previously, I use only http connection, and everything works perfectly.
This is my server
side:
app.js
const {ApolloServer, gql} = require('apollo-server-express');
const http = require('http');
const fs = require('fs');
const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors(), bodyParser.json());
const typeDefs = gql(fs.readFileSync('./schema.graphql', {encoding: 'utf8'}));
const resolvers = require('./resolvers');
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
});
apolloServer.applyMiddleware({app, path: '/graphql'});
const httpServer = http.createServer(app);
apolloServer.installSubscriptionHandlers(httpServer);
const port = 5000;
httpServer.listen(port, () => console.log(`Server started on port ${port}`));
This is the error:
I tried to google but it looks like an shortage of something in the webpack.config file of React but I don't know webpack. Please tell me how to deal with it, thank you so much and have a good day
Aucun commentaire:
Enregistrer un commentaire