koa2-cors 應用

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 後請求成功返回結果


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章