如何允许Koa的Access-Control-Allow-Origin

jim*_*m2k 3 node.js koa

我是Koa的新手,使用epxress时遇到一个问题。

这是我的代码:

const koa = require("koa");
const koaRouter = require("koa-router");
const app = new koa();
const router = new koaRouter();
const cors = require('koa-cors');
const bodyParser = require("body-parser");

const port = 8080;

app.use(router.routes()).use(router.allowedMethods());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

app.listen(port, () => {
  console.log("server koa started " + port);
});

router.get("/id/:id", async (ctx) => {
  const id = ctx.params.id;
  console.log("id was " + id);
  ctx.body = {
    "id": id
  }
});

router.get("/", async (ctx) => {
  ctx.body = {
    "message": "hello"
  }
});
Run Code Online (Sandbox Code Playgroud)

当我想从我的网络服务器上打电话时,我得到了这个:

Access to fetch at 'http://localhost:8080/id/azerty' 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.
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能解决这个问题?谢谢

小智 5

看到这里Koa cors模块

const Koa = require('koa');
const cors = require('@koa/cors');

const app = new Koa();
app.use(cors());
Run Code Online (Sandbox Code Playgroud)

您没有在代码中使用该模块。

  • 还值得一提的是 app.use(cors()) 必须在任何路由之前(即 app.use(router.routes()))。 (2认同)

小智 3

您需要 cors 模块,但尚未将 cors 添加到 app.use() 中间件。

app.use(cors())   // Add this new line 
app.use(router.routes()).use(router.allowedMethods());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
Run Code Online (Sandbox Code Playgroud)