how to allow Access-Control-Allow-Origin with koa
Asked Answered
V

2

15

I'm new to Koa and i encountered a problem that I didnt get when i used epxress.

here is my code :

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

Vamp answered 20/12, 2018 at 15:10 Comment(0)
H
18

see here Koa cors module

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.

Hulsey answered 20/12, 2018 at 17:22 Comment(2)
Also worth mentioning that app.use(cors()) has to go before ANY routes (i.e. app.use(router.routes())).Syphilis
@AndreasBergström saved me a lot of time.Trap
S
2

you required the cors module, but have not added cors to app.use() middleware.

app.use(cors())   // Add this new line 
app.use(router.routes()).use(router.allowedMethods());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
Seymourseys answered 20/12, 2018 at 17:16 Comment(1)
I did it, the problem came from chrome. We need to install Access-Control-Allow-Origin plugin in chrome then it worked ;)Vamp

© 2022 - 2024 — McMap. All rights reserved.