用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.)
望大家指点一二,谢谢
已解决 请求的地址忘记加http:// 真是尴尬