Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deno Oak Disable Cors

I am trying to 'connect' my small React JS app with my Deno API backend on my local environment with fetch().

   const apiUrl = `http://localhost:8000`;

   try{

    fetch(apiUrl)
      .then((res) => res.json())
      .then((repos) => {
        console.log(repos);
        setAppState({ loading: false, repos: repos });
      });
    }catch(err){
      console.log(err);
    }

My app is serving on localhost:3000 and my deno api on localost:8000.

However, I am having problem with CORS:

Access to fetch at 'http://localhost:8000/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I tried some suggestions like: add line '"proxy": "http://localhost:8000" to reactjs project packages.json'.

Or to add:

var options = {
    method: 'get',
    headers: {
        "Access-Control-Request-Headers": "*",
        "Access-Control-Request-Method": "*"
    },
  }

fetch(apiUrl, options)

Or to add:

fetch(apiUrl, {mode: 'no-cors'})

However, nothing works in my case. All the time getting the same error and some additional based on suggestions.

So,I need to disable CORS in my reactjs and deno api app to allow local dev communication between frontend and backend.

like image 856
Nezir Avatar asked Jun 10 '20 10:06

Nezir


Video Answer


3 Answers

Solution in my case was pretty easy.

I had to import oakCors into my Deno API app.ts

import { oakCors } from "https://deno.land/x/cors/mod.ts";

after that, just add the excluded origin after app instantiation:

app.use(
    oakCors({
      origin: "http://localhost:3000"
    }),
);

NOTE: I tried to set origin to origin: false and that did not work in my case.

For more options on Deno CORS here is a link: https://deno.land/x/cors

like image 179
Nezir Avatar answered Oct 14 '22 06:10

Nezir


For me, I had to first pass oakCors configuration to the app and then the routes.

app.use(oakCors({
    origin: 'http://localhost:4200',
    optionsSuccessStatus: 200,
}));
app.use(router.routes());
like image 2
Benko Avatar answered Oct 14 '22 05:10

Benko


This works just fine:

app.use(oakCors({ origin: "*" }));
like image 2
Zoman Avatar answered Oct 14 '22 07:10

Zoman