gpt4 book ai didi

node.js - 如何使用 koa 允许访问控制允许来源

转载 作者:搜寻专家 更新时间:2023-11-01 00:16:07 24 4
gpt4 key购买 nike

我是 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"
}
});

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

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.

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

最佳答案

看这里Koa cors module

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

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

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

关于node.js - 如何使用 koa 允许访问控制允许来源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53871292/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com