koa2-cors 应用:
用于设置允许跨域
案例:
后台代码
const Koa = require('koa');
const Cors = require('koa2-cors');
const App = new Koa()App.use(Cors());App.use((ctx)=>{if(ctx.url == '/'){ctx.body = "home"}
});App.listen(3000,function () {console.log('quick start at port 3000')
})
前端链接:http://localhost:63342/test2.html 及代码:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>测试renderApi</title><script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<a href="test.html">test</a>
<script>window.onload = function () {axios({method: 'get',url: 'http://localhost:3000/',}).then(res=>{console.log(res)}).catch(err=>{console.log(err)})}</script>
</body>
</html>
当我们访问http://localhost:63342/test2.html 后请求成功返回结果