node.js模拟jsonp

<!--
 * @Description: index.html
 * @Version: 1.0
 * @Autor: Nanke_南柯
 * @Date: 2021-10-31 23:19:43
 * @LastEditors: Nanke_南柯
 * @LastEditTime: 2021-10-31 23:36:31
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jsonp</title>
</head>
<body>
<script>
    function getData(data){
        console.log(data);
    }
</script>
<script src="http://localhost:5080/api/data?cb=getData"></script>
</body>
</html>
/*
 * @Description: index.js
 * @Version: 1.0
 * @Autor: Nanke_南柯
 * @Date: 2021-10-31 23:19:27
 * @LastEditors: Nanke_南柯
 * @LastEditTime: 2021-10-31 23:36:25
 */

const http = require('http');
const url = require('url');

const server  = http.createServer((req,res)=>{
    let urlStr = req.url;
    let uslObj = url.parse(urlStr,true)
    switch(uslObj.pathname){
        case '/api/data':
            res.write(`${uslObj.query.cb}("hello")`)
        break;
        default:
            res.write('page not found')
    }
    res.end()
})

server.listen(5080,()=>{
    console.log('localhost:5080 Listen');
})

 

posted @ 2021-10-31 23:39  南柯Dream丶  阅读(43)  评论(0)    收藏  举报