koa接口跨域报错

用koa+mongodb写了几个接口,用ajax请求时总是跨域报错,koa中用了cors也不行,谷歌了好多还是没有解决问题

const cors = require('koa2-cors');
var MongoClient = require("mongodb").MongoClient;
var DB_URL = "mongodb://localhost:27017/test";
// app.use(cors());
app.use(cors({
    origin: function (ctx) {
            return "*"; // 允许来自所有域名请求
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))
//省略封装的函数代码
app.use(router['routes']());
router.get('/',findFn)
router.get('/add',insertFn)
app.listen(3000);

接口截图

请求页面截图

接口请求头信息

让我的localhost:1234/index.html页面里请求localhost:3000的接口就会报如上图的错误(Failed to load localhost:3000: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.)

望大家指点一二,谢谢

阅读 2.5k
3 个回答

已解决 请求的地址忘记加http:// 真是尴尬

你的错误不是跨域的错误,看起来是你直接本地打开发的请求,起个服务打开试试

response上看不是后端代码的问题,贴一下前端代码,错误信息说only supported for protocol schemes:http, data, chrome, chrome-extension, https,怀疑是你scheme写错。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题