Deno Oak Disable Cors
Asked Answered
L

5

10

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.

Lento answered 10/6, 2020 at 10:39 Comment(3)
I have same issue above and no Deno solution below working? have u fixed it at Deno? – Condensable
This helped me, and this SO post was the first search result in DuckDuckGo on query 'deno oak cors'. However the OP misunderstands CORS or at least misformulated the question as CORS is 'Cross Origin Resource Sharing' and is something that needed to be ENabled to allow the front-end to backend communication, not DISabled as the question or subject now says. Please update. – Mccormack
Or perhaps don't update as many people are confused about CORS, since it is a hard concept to grasp. 😊 To clarify: what you can DISable is the 'Same-Origin policy' which all browser normally enforce. But this can NOT be disabled on the client side with a 'no-cors' indication or something but only server side, which the accepted answer explains how to do in Deno Oak. – Mccormack
L
10

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

Lento answered 10/6, 2020 at 10:39 Comment(3)
It still doesn't seem to work. Is there a chance there's something wrong with the react app? – Carmen
I think "false" won't work because your browser expect CORS, so you might need to also add "no-cors". ["*", "localhost:3000"] worked for me – Sworn
In my case this worked but oakCors had to be defined ABOVE app.use(router.routes()) in case you're using Oak's Router. – Relevance
P
6

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());
Poole answered 2/7, 2020 at 8:47 Comment(0)
L
5

This works just fine:

app.use(oakCors({ origin: "*" }));
Lepley answered 23/12, 2020 at 21:18 Comment(0)
G
1

You can use this:

app.use(async (ctx, next) => {
 ctx.response.headers.set('Access-Control-Allow-Origin', '*'); // * for all servers, you can use your own server address
 ctx.response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); // Which methods you want to allow
 ctx.response.headers.set('Access-Control-Allow-Headers', 'Content-Type'); // If your request body has json
 await next(); // If you use async await in other middlewares, you must use async await here
});
Geisha answered 12/11, 2023 at 0:10 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center. – Expanded
E
-4

placeapp.use(oakCors()) before your routes like this:

app.use(oakCors())
app.use(route.routes())

this is allow all CORS before to manage the routes

Eolanda answered 30/6, 2020 at 16:21 Comment(0)

© 2022 - 2025 β€” McMap. All rights reserved.