问题
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.
回答1:
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
回答2:
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());
回答3:
This works just fine:
app.use(oakCors({ origin: "*" }));
回答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
来源:https://stackoverflow.com/questions/62301531/deno-oak-disable-cors