Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React js - problem with proxy for web socket link in react

I am setting up the proxy server using setupProxy for my react app using graphql as backend which is running on a different part, doing so The HTTP link proxy is working fine but WebSocket link proxy is giving me an error

For solving the problem I have tried to include options as ws: true, but it's not working. The error is as follows: SyntaxError: Failed to construct 'WebSocket': The URL '/ws' is invalid.

Error:

enter image description here

setupProxy.js

const proxy = require("http-proxy-middleware");

module.exports = function(app) {
  app.use(proxy("/graphql", { target: "http://localhost:8001/graphql" }));
  app.use(
    proxy("/ws", {
      target: "ws://localhost:8001",
      ws: true,
    })
  );
};

index.js

import { WebSocketLink } from "apollo-link-ws";
import { createUploadLink } from "apollo-upload-client";
//Apollo Imports End

// Declaring constants for GraphQL
const httpLink = new createUploadLink({
  uri: "/graphql"
});

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

I expected the call should be same as normal call but its throwing an error.

like image 269
EvilsEmpire Avatar asked May 25 '19 09:05

EvilsEmpire


2 Answers

/ws is not a valid URI for a WebSocket class. A websocket expect a full URL to connect, you can try it in your browser console:

enter image description here

In this case, Apollo is using the native web socket class behind the scenes, so if you can make this work, it will work in Apollo too.

Try using ws://localhost:8001 instead.

like image 145
glneto Avatar answered Oct 09 '22 18:10

glneto


Just replace with this

const proxy = require("http-proxy-middleware");

module.exports = function(app) {
  app.use(proxy("/graphql", { target: "http://localhost:8001/graphql" }));
  app.use(proxy("ws://locahost:8001"));
};

OR

const proxy = require("http-proxy-middleware");

module.exports = function(app) {
  app.use(proxy("/graphql", { target: "http://localhost:8001/graphql" }));
  app.use(proxy('/ws', {
   target: 'http://localhost:8001',
   ws: true
  })
 );
};
like image 1
Aritra Ghosh Avatar answered Oct 09 '22 19:10

Aritra Ghosh