question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

WebSocket connection to 'ws://localhost:4000/' failed: Error during WebSocket handshake: Unexpected response code: 400

See original GitHub issue

I can’t figure out what is the problem?

server:

const {ApolloServer, gql, PubSub} = require("apollo-server");
const pubsub = new PubSub();

const typeDefs = gql`
    type Subscription {
        postHello: String!
    }
    
    type Query {
        hello(id: Int!): String!
    }
    
    type Mutation {
        addHello(hello: String!): String!
    }
`;

const POST_ADDED = 'POST_ADDED';

const resolvers = {
    Subscription: {
        postHello: {
            subscribe: () => pubsub.asyncIterator([POST_ADDED])
        }
    },

    Query: {
        hello (obj, args) {
            const arr = ["aaaaaa", "bbbbb", "cccccccc"];
            return arr[args.id]
        }
    },

    Mutation: {
        async addHello (obj, args) {
            await pubsub.publish(POST_ADDED, {postHello: args.hello})

            return args.hello
        }
    }
};

const server = new ApolloServer({typeDefs, resolvers});

server.listen().then(({ url }) => {
    console.log(`🚀  Server ready at ${url}`);
});

client:

import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloProvider, Query } from 'react-apollo';
import gql from 'graphql-tag'
import { ApolloClient } from 'apollo-client';
import { getMainDefinition } from 'apollo-utilities';
import { ApolloLink, split } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
import { InMemoryCache } from 'apollo-cache-inmemory';

import App from './components/App';

const httpLink = new HttpLink({
    uri: 'http://localhost:4000',
});

const wsLink = new WebSocketLink({
    uri: `ws://localhost:4000`,
    options: {
        reconnect: true,
    },
});

const terminatingLink = split(
    ({ query }) => {
        const { kind, operation } = getMainDefinition(query);
        return (
            kind === 'OperationDefinition' && operation === 'subscription'
        );
    },
    wsLink,
    httpLink,
);

const link = ApolloLink.from([terminatingLink]);

const cache = new InMemoryCache();

const client = new ApolloClient({
    link,
    cache,
});

ReactDOM.render(
    <ApolloProvider client={client}>
        <App />
        <Query query={
            gql`
                {
                hello(id: 1)
                }           
`
        }>

            {({ loading, error, data }) => {
                if (loading) return <p>Loading...</p>;
                if (error) return <p>Error :(</p>;

                return <p>{data.hello}</p>
            }}

        </Query>
    </ApolloProvider>,
    document.getElementById('root'),
);

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:3
  • Comments:18 (1 by maintainers)

github_iconTop GitHub Comments

31reactions
vincenterccommented, Jul 9, 2019

try ‘ws://localhost:4000/graphql’

23reactions
danieldunderfeltcommented, Oct 8, 2020

My problem was that I am using an Express server and applying Apollo Server as a middleware. I was not aware that I need to call graphqlServer.installSubscriptionHandlers(expressServer) too, as this was buried deep in the docs. That needs to be called on the HTTP server instance you get returned from expressApp.listen(). Now it is working!

Read more comments on GitHub >

github_iconTop Results From Across the Web

WebSocket connection failed: Error during ... - Stack Overflow
WebSocket connection failed : Error during WebSocket handshake: Unexpected response code: 400 · Ask Question. Asked 5 years, 11 months ago.
Read more >
Error during WebSocket handshake: Unexpected ... - GitHub
Can't find out a solution, I get this error on the browser console: WebSocket connection to 'ws://.../socket.io/?
Read more >
Asked by Cimmanuel - DigitalOcean
WebSocket connection to 'wss://api-such.andsuch.xyz/graphql/' failed: Error during WebSocket handshake: Unexpected response code: 400.
Read more >
Got connection failed: Error during WebSocket handshake ...
Help~ Got connection failed: Error during WebSocket handshake: Unexpected response code: 400 ... I have a problem connecting to the photon server ...
Read more >
Error during WebSocket handshake: Unexpected response ...
WebSocket connection to 'wss://my_domain/openvidu' failed: Error during WebSocket handshake: Unexpected response code: 400. How can I fix this error?
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found