cors-anywhere icon indicating copy to clipboard operation
cors-anywhere copied to clipboard

Does not work in Deno (TypeError on every request)

Open Pyroglyph opened this issue 2 years ago • 1 comments

Simple usage does not work at all in Deno. Every request ends in the same TypeError.

Example using PokeAPI:

// cors.ts
import corsProxy from 'npm:cors-anywhere';
corsProxy.createServer().listen(8080, 'localhost', () => {
    console.log('Running CORS Anywhere');
    fetch('http://localhost:8080/pokeapi.co:443/api/v2/');
});

Result:

❯ deno run --allow-net cors.ts
Running CORS Anywhere
TypeError: Cannot read properties of undefined (reading 'encrypted')
    at ServerImpl.<anonymous> (file:///home/pyro/.cache/deno/npm/registry.npmjs.org/cors-anywhere/0.4.4/lib/cors-anywhere.js:384:47)
    at ServerImpl.emit (https://deno.land/[email protected]/node/_events.mjs:379:28)
    at https://deno.land/[email protected]/node/http.ts:634:16
    at new Promise (<anonymous>)
    at handler (https://deno.land/[email protected]/node/http.ts:632:16)
    at Object.serve (internal:ext/flash/01_http.js:572:24)
    at async Promise.all (index 0)
    at async serve (internal:ext/flash/01_http.js:688:7)

Not even the sample URLs given in the readme work. Navigating to / works if you launch Deno with --allow-read, and so does /iscorsneeded. Nothing else works though.

Pyroglyph avatar Feb 09 '23 14:02 Pyroglyph

After more investigating, it appears that the connection property is not present on req when this is run through Deno.

Simply changing this line

var isRequestedOverHttps = req.connection.encrypted || /^\s*https/.test(req.headers['x-forwarded-proto']);

to this

var isRequestedOverHttps = req.connection?.encrypted || /^\s*https/.test(req.headers['x-forwarded-proto']);
                                         ^

should solve the issue.

Pyroglyph avatar Feb 10 '23 09:02 Pyroglyph