本文介绍了如何使用koa允许Access-Control-Allow-Origin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Koa的新手,遇到了使用epxress时没有遇到的问题.

I'm new to Koa and i encountered a problem that I didnt get when i used 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"
  }
});

当我想从我的网络服务器上调用它时,我得到了这个信息:

when I want to call this from my webserver i got this :

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.

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

What can I do to solve this problem ?Thanks

推荐答案

请参见此处 Koa cors模块

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

const app = new Koa();
app.use(cors());

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

You're not using the module in your code.

这篇关于如何使用koa允许Access-Control-Allow-Origin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 12:06