Deno Oak 禁用 Cors

Deno Oak Disable Cors

我正在尝试 'connect' 我的小型 React JS 应用程序和我的 Deno API 后端在我的本地环境 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);
    }

我的应用程序在 localhost:3000 上运行,我的 deno api 在 localost:8000 上运行。

但是,我在使用 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.

我尝试了一些建议,例如: 将行 '"proxy": "http://localhost:8000" 添加到 reactjs 项目 packages.json'.

或添加:

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

fetch(apiUrl, options)

或添加:

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

但是,我的情况没有任何效果。总是得到相同的错误和一些基于建议的额外错误。

所以,我需要在我的 reactjs 和 deno api 应用程序中禁用 CORS,以允许前端和后端之间的本地开发通信。

我的解决方案非常简单。

我不得不将 oakCors 导入我的 Deno API app.ts

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

之后,只需在应用程序实例化后添加排除源:

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

注意:我尝试将原点设置为 origin: false,但这对我来说不起作用。

有关 Deno CORS 的更多选项,这里是 link:https://deno.land/x/cors

app.use(oakCors())放在你的路线之前:

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

这是允许之前的所有 CORS 管理路由

对我来说,我必须先将 oakCors 配置传递给应用程序,然后再传递路由。

app.use(oakCors({
    origin: 'http://localhost:4200',
    optionsSuccessStatus: 200,
}));
app.use(router.routes());

这很好用:

app.use(oakCors({ origin: "*" }));