D
Deno

help

Can't upgrade request to websocket

FFjordWarden10/25/2023
I want to use a websocket in one of my middlewares. But I keep getting an error saying I can't upgrade my connection:
[uncaught application error]: TypeError - Invalid Header: 'upgrade' header must contain 'websocket'
[uncaught application error]: TypeError - Invalid Header: 'upgrade' header must contain 'websocket'
I've googled this error but only find old results relating this error to the version of deno or oak lib where I run the latest deno (1.37.2) and oak (12.6.1).
import {Application,Router} from 'https://deno.land/x/oak@v12.6.1/mod.ts'

function RefreshMiddleware() {
return async (ctx,next) => {
console.log('url',ctx.request.url.href)
if (ctx.request.url.href.endsWith("/refresh")) {
console.log(ctx.isUpgradable);
console.log(ctx.request.headers.get("connection"));
const socket = ctx.upgrade()
} else next()
}
}

const app = new Application()
app.addEventListener("error", e => console.error(e.error))

// Logger
app.use(async (ctx, next) => {
const start = Date.now()
await next()
console.log(`${ctx.request.method} ${ctx.request.url} - ${Date.now() - start}ms`)
})
app.use(RefreshMiddleware())
app.use((ctx) => {ctx.response.body = "Hello World!"})

await app.listen({port: 8000})
import {Application,Router} from 'https://deno.land/x/oak@v12.6.1/mod.ts'

function RefreshMiddleware() {
return async (ctx,next) => {
console.log('url',ctx.request.url.href)
if (ctx.request.url.href.endsWith("/refresh")) {
console.log(ctx.isUpgradable);
console.log(ctx.request.headers.get("connection"));
const socket = ctx.upgrade()
} else next()
}
}

const app = new Application()
app.addEventListener("error", e => console.error(e.error))

// Logger
app.use(async (ctx, next) => {
const start = Date.now()
await next()
console.log(`${ctx.request.method} ${ctx.request.url} - ${Date.now() - start}ms`)
})
app.use(RefreshMiddleware())
app.use((ctx) => {ctx.response.body = "Hello World!"})

await app.listen({port: 8000})
Eeric.uhd10/25/2023
if (req.headers.get("upgrade") != "websocket") {
return new Response(null, { status: 501 });
}
const { socket, response } = Deno.upgradeWebSocket(req);
socket.addEventListener("open", () => {
console.log("a client connected!");
});
socket.addEventListener("message", (event) => {
if (event.data === "ping") {
socket.send("pong");
}
});
return response;
if (req.headers.get("upgrade") != "websocket") {
return new Response(null, { status: 501 });
}
const { socket, response } = Deno.upgradeWebSocket(req);
socket.addEventListener("open", () => {
console.log("a client connected!");
});
socket.addEventListener("message", (event) => {
if (event.data === "ping") {
socket.send("pong");
}
});
return response;
FFjordWarden10/26/2023
Yes, that works but I'm trying to migrate to oak . I can't imagine what I am doing wrong as I am just following the documentation.
Eeric.uhd10/26/2023
You just said: that works Then: what I am doing wrong I'm confused
FFjordWarden10/26/2023
I want to use oak
Eeric.uhd10/26/2023
Just use it, there no OAK way, or Fresh Way to use WebSocket, just the Deno way: https://discord.com/channels/684898665143206084/1166876166741819452/1166888108231512085
FFjordWarden10/26/2023
Look, for some reason I keep having issues just running the example code. if I run the example from the blog, I just added an explicit version number, it still doesn't work:
import { Application, Router } from "https://deno.land/x/oak@v12.6.1/mod.ts";
const app = new Application({ logErrors: false });
const router = new Router();
router.get("/wss", (ctx) => {
if (!ctx.isUpgradable) {
ctx.throw(501);
}
const ws = ctx.upgrade();
ws.onopen = () => {
console.log("Connected to client");
ws.send("Hello from server!");
};
ws.onmessage = (m) => {
console.log("Got message from client: ", m.data);
ws.send(m.data);
ws.close();
};
ws.onclose = () => console.log("Disconncted from client");
});
app.use(router.routes());
app.use(router.allowedMethods());
app.listen({ port: 8000 });
import { Application, Router } from "https://deno.land/x/oak@v12.6.1/mod.ts";
const app = new Application({ logErrors: false });
const router = new Router();
router.get("/wss", (ctx) => {
if (!ctx.isUpgradable) {
ctx.throw(501);
}
const ws = ctx.upgrade();
ws.onopen = () => {
console.log("Connected to client");
ws.send("Hello from server!");
};
ws.onmessage = (m) => {
console.log("Got message from client: ", m.data);
ws.send(m.data);
ws.close();
};
ws.onclose = () => console.log("Disconncted from client");
});
app.use(router.routes());
app.use(router.allowedMethods());
app.listen({ port: 8000 });
The code does not run past if (!ctx.isUpgradable) ...
ABAltair 680b10/26/2023
This happens on server startup, or when a client connects?
FFjordWarden10/26/2023
Oh, ok sorry I get it know, that error is normal if you don't connect with a websocket...

Looking for more? Join the community!

Recommended Posts
Access `navigator.geolocation` in deno runtimeHello, is it possible to access `navigator.geolocation` in the deno runtime?Tracking Down Lost MemoryHi, I have a long running service that creates many `JsRuntime`s over time and I have found that I `deno run` ignores @deno-types?```ts Uncaught SyntaxError: The requested module 'pg' does not provide an export named 'Pool' importWhere is my Twitter access token with Deno KV Oauth?I signed in successfully and now the Deno KV database is just storing `true`. It's not enough to intHow do I import the stripe SDK into my fresh.js projectHi there! How do I import the stripe SDK into my fresh.js project? Im struggling with my deno.json fUnable to find NPM:Rollup 4.1.4 on M1 MacHi all, hooking up a new build process for UI project, trying to use Rollup on an M1 Mac. My build How to get custom folder structure with Fresh?Hello, I want to integrate Fresh into my existing project. I want to use the 4 directories: componenFresh error: Could not fetch latest versionTotal newbie here. I'm getting "Update check failed: Could not fetch latest version." when I make a VSCode Test Debugging```json { "name": "Test", "request": "launch", "type": "node", "cwd": "$Can you recommend a mysql driver for deno that isn't a complete dead end?mysql2 port: never updated. mysql driver: doesn't support strings mysql connector from Oracle: no onHelp with Slack CLI DeploymentSorry if this has already been answered, but I am trying to deploy my Slack app and I keep getting tOrganizing dependencies in workspace with several project folderSuppose you have a workspace with several folder, and in each folder you have a deno project. What iGitHub CLI from denoIs it possible/how to use the GitHub cli (gh) from JavaScript on deno? Using the `Github cli` I'm abHow can I change the port in Fresh?I have tried the following in the Main.ts await start(manifest, { port: 3000 }), But I suspect this Alternative to react-selectHello is there some alternative to react-select with fresh? I don't find any working with preact/frHow does Fresh run esbuild on Deploy without cache writes?I'm trying to build some solidjs code during runtime, but I keep getting errors on Deploy because ofPyCharm notebooks syntax highlightHello. I have set up Deno to work with pycharm. I am able to run a jupyter server with Deno kernel swasmbuild & rust module pathI try to call some rust modules in a wasm project https://deno.com/blog/wasmbuild My tree project iDeno does not recognize ".node" extension files**[name].node** is C++ *(kind of)* [addons](https://nodejs.org/api/addons.html#addons_loading_addonsCan use the --cert flag in the command line, but not in deno.jsonI am trying to run my deno program with the following command: `deno run -A --cert ~/tmp/ca.crt main