Connection refused when requesting Deno server (with oak middleware) from NextJS api routes

346 Views Asked by At

I'm trying to request Deno server from next api routes. To simplify (with the same result), let's assume we have server written with oak middleware like:

import { Application } from 'https://deno.land/x/oak/mod.ts'
import { oakCors } from 'https://deno.land/x/cors/mod.ts'

const app = new Application()

app.use(
  oakCors({
    origin: 'http://localhost:3000',
    credentials: true
  })
)

app.use((ctx) => {
  ctx.response.body = 'Hello World!'
})

await app.listen({ port: 3001 });

oakCors are added to alow cors from http://localhost:3000, where next app will be running. Let's run simple next app where in the /page/api/test.js a request to http://localhost:3001 is implemented:

export default async function handler(req, res) {
  try {
    const data = await fetch('http://localhost:3001')
    console.log(data)
  } catch (e) {
    console.log(e)
  }

  res.json({ done: true })
}

So, now if we render 2 buttons:

<button onClick={() => fetch('http://localhost:3001')}>direct fetch</button>
<button onClick={() => fetch('api/test')}>fetch by api routes</button>

Where the first button requests http://localhost:3001 directly, and the second one requests test api route (which in turn requests http://localhost:3001).

In the first case (direct fetch) everything is ok. In the second case, there is an error in the next server console:

error - unhandledRejection: TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:14062:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: Error: connect ECONNREFUSED 127.0.0.1:3001
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1487:16) {
    errno: -111,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 3001
  }
}

Question: why connection is refused in the second case and how to fix it?

Additionally: If a ngrok tunnel is run for http://localhost:3001

ngrok http 3001

requests work through this tunnel in both cases (using generated tunnel url).

0

There are 0 best solutions below