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:
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.
/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:
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.
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
})
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With